简体   繁体   English

如何使用python cron-tab安排每日,每月,每周的cron作业?

[英]How to schedule daily, monthly, weekly cron jobs using python cron-tab?

I need to run a cron job daily, weekly, monthly using python. 我需要每天,每周,每月使用python运行cron作业。 I did much research and decided to go with crontab. 我做了很多研究,并决定使用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. 在这里,每个人每天,每周和每月的取值分别为1d,1w,1m。 It can also take values as 2d, 2w, 2m, etc. I have identified the code for daily and monthly. 它还可以取值为2d,2w,2m等。我已经确定了每天和每月的代码。 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 每月一次,每月的1号

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 . 此WP页面解释了格式: 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM