设置 Linux cron 定时任务实现任务自动化处理

摘要

如果说你每天都需要做一些重复的工作,比如出一份报告、统计一个数据、发一封邮件等等这些涉及到日常工作的自动化处理,---新消息频道你完全可以把这个任务交给电脑让它每天自动替你完成。

正文

今天主要会用到Linux下的cron这个服务。

安装cron

基本上所有的Linux发行版在默认情况下都预安装了cron工具。

即使未预装cron,也很简单,执行几条简单的命令就可手动安装

安装并启动服务

#安装cronapt-get install cron -y

language-shell

# 查看cron工作状态service cron status#启动start/停止stop/重启restartservice cron start/stop/restart#查询当前任务:crontab -l

language-shell

cron用法

有几个关于cron的简单用法可以了解一下,后面也会通过一个案例详细介绍如何使用

首先,列出当前用户计划的cron作业:

crontab -l

language-shell

查看root用户的cron作业:

crontab –l –u root

language-shell

移除已经计划的cron作业:

crontab –r

language-shell

创建crontab计划

首先,通过如下命令 添加或更新crontab中的任务,第一次进入会要求你选择编辑器,这个根据自己的习惯选择。默认为VIM编辑器

crontab -e

language-shell

选择好之后会进入到这样的一个vim的界面。

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

用过vim的同学应该对这个界面不陌生,类似的操作: 按A键开始编辑,按ESC输入:wq保存并退出,crontab是会自动实时更新任务列表的。

重点是最下面的一段内容:

# m h  dom mon dow   command

这个其实就是crontab调度作业的一个使用介绍,可以用来设置定时任务。

具体一点的语法是这样的:

m h dom mon dow command
* * * * * command
- - - - - -
| | | | | |
| | | | | --- 预执行的命令
| | | | ----- 表示星期0~7(其中星期天可以用0或7表示)
| | | ------- 表示月份1~12
| | --------- 表示日期1~31
| ----------- 表示小时1~23(0表示0点)
------------- 表示分钟1~59 每分钟用*或者 */1表示

举几个简单的应用案例:

* * * * * XXX 每分钟运行。
0 * * * * XXX 每小时运行。
0 0 * * * XXX 每天零点运行。
0 9,18 * * * XXX在每天的9AM和6PM运行。
0 9-18 * * * XXX 在9AM到6PM的每个小时运行。
0 9-18 * * 1-5 XXX 周一到周五的9AM到6PM每小时运行。
*/10 * * * * XXX 每10分钟运行。
  • 每天 02:00 执行任务
0 2 * * * LinuxCommand
  • 每天 5:00和17:00执行任务
0 5,17 * * * LinuxCommand
  • 每 10min 执行一次任务
*/10 * * * * LinuxCommand
  • 在特定的某几个月的周日 17:00 执行任务
0 17 * jan,may,aug sun LinuxCommand

更多的使用案例还可以参考网络。

上面案例中的command 表示你具体需要执行的任务,建议所有的路径都填写绝对路径。

例如这段话输出到txt中:

echo "Hello Cron" >> /tmp/test.txt

或者是你需要执行一个Python脚本:

python demo.py filepath

后面的filepath表示输入的参数args,这个可能有的同学会用到。

完结

以上就是设置 Linux cron 定时任务实现任务自动化处理的所有内容,欢迎小伙伴们交流讨论。

相关文章

linux常用进程通信方式包括管道(pipe)、有名管道(FIFO)、...
Linux性能观测工具按类别可分为系统级别和进程级别,系统级别...
本文详细介绍了curl命令基础和高级用法,包括跳过https的证书...
本文包含作者工作中常用到的一些命令,用于诊断网络、磁盘占满...
linux的平均负载表示运行态和就绪态及不可中断状态(正在io)的...
CPU上下文频繁切换会导致系统性能下降,切换分为进程切换、线...