crontab 用法(执行python文件)[通俗易懂]

2022-09-23 11:20:33 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

前提:

  1. 创建一个xxx.py的文件 文件头为
代码语言:javascript复制
#!/usr/bin/python3
# -*- conding= utf-8 -*-
print('hello world')
  1. 更改权限
代码语言:javascript复制
chmod 777 xxx.py 

这样python文件就可以执行了

代码语言:javascript复制
ubuntu@VM-0-10-ubuntu:~/script$ ./test.py
hello world

crontab 使用

  1. 编辑、添加crontab crontab -e 第一次执行会让用户选择编辑器,自己根据喜好选择编辑器 进入编辑会显示如下代码:
代码语言:javascript复制
  1 # Edit this file to introduce tasks to be run by cron.
  2 #
  3 # Each task to run has to be defined through a single line
  4 # indicating with different fields when the task will be run
  5 # and what command to run for the task
  6 #
  7 # To define the time you can provide concrete values for
  8 # minute (m), hour (h), day of month (dom), month (mon),
  9 # and day of week (dow) or use '*' in these fields (for 'any').#
 10 # Notice that tasks will be started based on the cron's system
 11 # daemon's notion of time and timezones.
 12 #
 13 # Output of the crontab jobs (including errors) is sent through
 14 # email to the user the crontab file belongs to (unless redirected).
 15 #
 16 # For example, you can run a backup of all your user accounts
 17 # at 5 a.m every week with:
 18 # 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
 19 #
 20 # For more information see the manual pages of crontab(5) and cron(8)
 21 #
 22 # m h dom mon dow command
 23 #* * * * * /home/ubuntu/python/Simple_review_system/component/emailer.sh >> /home/ubuntu/script/review_emailer.log 2 >&1
~           
  1. 查看crontab命令 crontab -l
  2. 定时执行任务
  • 命令行输入crontab -e:进入crontab编辑模式
  • 在文件末添加要定时执行的代码 格式:{minute} {hour} {day-of-month} {month} {day-of-week} {full-path-to-shell-script} ( >> {full-path-to/xxx.log 2>&1}) (括号里面可选项,添加日志)
  • minute: 0-59
  • hour: 0-23
  • day-of-month: 0-31
  • month : 1-12
  • day-of-week: 0-7 (*表示每分钟,每小时,每…)

示例:

  • 每天02:00执行任务 0 2 * * * /path/xxx.py
  • 每天5:00和17:00执行任务 0 5,17 * * * /path/xxx.py
  • 每分钟执行一次任务 * * * * * /path/xxx.py
  • 每周日17:00执行任务 0 17 * * sun /path/xxx.py
  • 每10分钟执行一次任务 */10 * * * * /path/xxx.py
  • 在特定的某几个月执行任务 * * *jan,may,aug * /path/xxx.py
  • 每30秒执行一次任务 * * * * * /path/xxx.py * * * * * sleep 30; /path/xxx.py

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/172606.html原文链接:https://javaforall.cn

0 人点赞