0

I need to run a cron job daily, weekly, monthly using python. I did much research and decided to go with crontab. This is my configuration :

"schedule" :  {
  "name": "xyz",
  "at": "12:00:00 AM",
  "every": "1d"
  } 

Here, every can take the value of 1d, 1w, 1m for daily, weekly, monthly. It can also take values as 2d, 2w, 2m, etc. I have identified the code for daily and monthly. I am stuck with weekly. Can anyone help ?

my_cron = CronTab(user=self.user)
        for job in my_cron :
            if job.comment == self.name:
                my_cron .remove(job)
                my_cron .write()
        job = my_cron .new(
            command='sh start.sh "invoke-adapter"',
            comment=self.name)        
        job.setall(str_job_schedule)
        vmware_cron.write()

For monthly, str_job_schedule = "30 03 * */1 *" (runs every month)
For daily, str_job_schedule = "30 03 * * */1" (runs every day)
For weekly, str_job_schedule = "30 03 ? * *" 
Jérôme
  • 13,328
  • 7
  • 56
  • 106
Malar Kandasamy
  • 839
  • 2
  • 10
  • 17

2 Answers2

1

I would specify which day I want:

For monthly, every 1st of the month

str_job_schedule = "30 03 1 * *"

For daily, everyday at midnight

str_job_schedule = "30 03 * * *"

For weekly, every sunday

str_job_schedule = "30 03 * * 0"

This WP page explains the format: https://en.wikipedia.org/wiki/Cron.

Jérôme
  • 13,328
  • 7
  • 56
  • 106
  • Thanks. Let me try this. How to specify run every alternate days or once in 3 days ? – Malar Kandasamy Jan 14 '19 at 10:21
  • There is no perfect way for that. See https://serverfault.com/questions/204265/how-to-configure-cron-job-to-run-every-2-days-at-11pm. */2 in third column runs every odd day, but it will run on 31st and 1st. AFAIK, crontab does not allow alternate days. You could add the logic in your script as suggested in https://serverfault.com/a/204280/292268. – Jérôme Jan 14 '19 at 10:53
0

I did very similar thing and basicly created kind of scheduler. I will show you approximatly the idea

import threading
from crontab import CronTab
import time
schedules = {'Jobs': {'clean house': '* * * * *'}, {'cook': '*/5 * * * *'}} # some kind of config of your jobs

while True:
    time.sleep(11)
    for job in schedules['Jobs']:
        entry = CronTab(schedules['Jobs'][job])
        if entry.next() < 9:
            # if the job is going to happen in less than 10s
            # run thread which will execute after time.sleep(entry.next())
            threading.Thread(target = execute,args=(job,)).start()
Martin
  • 3,333
  • 2
  • 18
  • 39