DEV Community

Cover image for Create k8s Cronjob To Schedule Delete Expired Files
🚀 Vu Dao 🚀
🚀 Vu Dao 🚀

Posted on • Edited on

Create k8s Cronjob To Schedule Delete Expired Files

  • Application service processes documents and stores them in EFS volume as their cache, the requirement is to clear files which is older than 7 days.

  • Solution: Create a cronjob with expected schedule time, the cronjob will claim a volume of same EFS persistent volume and then check time life of the files.
    Alt Text

  • Note:
    -- The service mount path: /app/ and stores files in /app/Documents
    -- The cronjob should mount path: /opt/demo/ and then it can see Documents

demo.yaml



apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: demo-clean
spec:
  schedule: "0 1 * * SAT"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: demo-clean
            image: busybox
            args:
            - /bin/sh
            - -c
            - find /opt/demo/Documents/ -type f -mtime +7 -exec rm {} \;
            volumeMounts:
            - name: efs
              mountPath: "/opt/demo/"

          restartPolicy: OnFailure
          volumes:
          - name: efs
            persistentVolumeClaim:
              claimName: efs-pvc


Enter fullscreen mode Exit fullscreen mode

Apply yaml file and check



~:/# kubectl get cronjob
NAME              SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
demo-clean          0 1 * * SAT   False     0        30h             9d

~:/# kubectl get pod
demo-clean-1607838120-7kl2w                            0/1     Completed   0          18h


Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
pitisheur profile image
pitisheur

Hi @vumdao !

I have followed your code, but I need a full picture of your .yml file.
I have a deployment (container) that creates .csv files inside the pod.
I need to create a CronJob to mount the pod's volume and clean the older .csv files from time to time.
I just can't figure it out exactly about how to configure the volume for the deployment and get it working with the persistentVolumeClaim from the Cronjob.

Can you please share your full .yaml configuration and/or help me with this task ?
Thanks !

Collapse
 
routinggames profile image
Duy Nguy3n

thank you, it's very useful.

Collapse
 
epp1628 profile image
epp1628

I am getting the error : find: -exec requires an argument

Collapse
 
vumdao profile image
🚀 Vu Dao 🚀

What is your full command?