Friends who are familiar with Linux should know that you can use Crontab to set up scheduled tasks in Linux. You can write tasks by command crontab-e. Of course, you can also write the configuration file settings task directly.
But sometimes you want to automate the setup of scripts, such as when our application is deployed. There is a need, of course, to find a solution, or in the program Ape-bound (a group of the ape).
The following goes to the point, and began to want to write in the form of a file, by appending a line directly in the configuration file. However, it is difficult to read and write files, such as: To set the task to check whether the task already exists, according to the input parameters to set the corresponding task. It is not appropriate to read and write files. So think of the "Magnum" of the Big Python.
As when, today's protagonist plays: Python-crontab module. Install Direct
?
1 |
$ pip install python - crontab |
The following script will make it easy to set up scheduled tasks.
?
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
from crontab
import CronTab
# 创建当前用户的crontab,当然也可以创建其他用户的,但得有足够权限
my_user_cron
= CronTab(user
=
True
)
# 创建任务
job
= my_user_cron.new(command
=
‘echo date >> ~/time.log‘
)
# 设置任务执行周期,每两分钟执行一次
job.setall(
‘*/2 * * * *‘
)
# 当然还支持其他更人性化的设置方式,简单列举一些
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
))
# 同时可以给任务设置comment,这样就可以根据comment查询,很方便
job.set_comment(
"time log job"
)
# 根据comment查询,当时返回值是一个生成器对象,不能直接根据返回值判断任务是否#存在,如果只是判断任务是否存在,可直接遍历my_user_cron.crons
iter = my_user_cron.find_comment(
‘time log job‘
)
# 同时还支持根据command和执行周期查找,基本类似,不再列举
# 任务的disable和enable, 默认enable
job.enable(
False
)
job.enable()
# 最后将crontab写入配置文件
my_user_cron.write()
|
The following commands can be used to see if the creation was successful:
?
Very convenient, and some features are not fully introduced, you can refer to the official document Https://pypi.python.org/pypi/python-crontab
The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support the script home.
About setting up Linux timed tasks using Python crontab