The linux timing task is set using python crontab

  • 2020-05-17 05:55:36
  • OfStack

Anyone familiar with linux should know that you can use crontab in linux to set up timed tasks. You can write tasks by ordering crontab-e. You can also write configuration files directly to set up tasks.

But there are times when you want to set things up automatically with a script, such as when your application is deployed. If there is a need, you have to find a way to deal with it, or you'll end up in the programming ape world (1 group of apes enjoying themselves).

Let's get down to business and start by setting it as a write file, by appending 1 line directly to the configuration file. However, it is difficult to read and write files. For example, when setting a task, it is necessary to check whether the task already exists. Set the corresponding tasks according to the input parameters. It is not always appropriate to read or write files. So I thought of the "all-purpose" big python.

Dang dang, today's leading actor: python-crontab module. Installed directly


$ pip install python-crontab

The following script makes it easy to set up the scheduled tasks


from crontab import CronTab

#  Create the current user's crontab Of course, you can create another user's, but only if you have enough permissions 

my_user_cron = CronTab(user=True)

#  Create a task 

job = my_user_cron.new(command='echo date >> ~/time.log')

#  Set the task execution cycle to run every two minutes 1 time 

job.setall('*/2 * * * *')

#  Of course, other more user-friendly Settings are also supported, simply listed 1 some 

job.minute.during(5,50).every(5)

job.hour.every(4)

job.day.on(4, 5, 6)

job.dow.on('SUN')

job.dow.on('SUN', 'FRI')

job.month.during('APR', 'NOV')

job.setall(time(10, 2))

job.setall(date(2000, 4, 2))

job.setall(datetime(2000, 4, 2, 10, 2))

#  You can also set tasks comment So that's the basis comment Inquiry, very convenient 

job.set_comment("time log job")

#  According to the comment Query, when the return value is 1 You cannot directly determine whether a task is or is not based on the return value # Existing, if only to determine whether the task exists, can be directly traversed my_user_cron.crons

iter = my_user_cron.find_comment('time log job')

#  It also supports the basis command And execution cycle lookup, basically similar, no more enumerations 

#  The task of disable and enable .   The default enable

job.enable(False)

job.enable()

#  The final will be crontab Write configuration file 

my_user_cron.write() 

The following command can be seen to see if the creation was successful:


$ crontab -l

Very convenient, there are some features not 1, you can refer to the official documentation https: / / pypi python. org/pypi/python - crontab


Related articles: