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 ? * *"
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 .
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.