DEV Community 👩‍💻👨‍💻

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

Posted on • Updated 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 (3)

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 🚀 Author

What is your full command?

🌚 Life is too short to browse without dark mode