引言
Cron是Linux系统中用于定时执行任务的工具,它允许用户按照预定的时间间隔自动运行脚本或程序。Ubuntu 18.04作为一款流行的Linux发行版,内置了Cron服务。本文将详细介绍Ubuntu 18.04版Cron定时任务的基本使用方法,并分享一些高级技巧。
入门指南
1. 启动和配置Cron服务
在Ubuntu 18.04中,Cron服务默认是启动的。你可以使用以下命令检查Cron服务状态:
sudo systemctl status cron
如果服务未启动,可以使用以下命令启动:
sudo systemctl start cron
2. 编辑Cron任务
Cron任务存储在
/etc/crontab
文件中,或者每个用户的
~/.crontab
文件中。以下是如何编辑
/etc/crontab
文件的示例:
sudo nano /etc/crontab
在这个文件中,你可以看到类似以下的行:
# /etc/crontab: root’s crontab file.
# Edit this file to change the root cron job timing.
# Each line must have at least five fields. No fields may be empty.
# Nor may a field contain white space, except the first field.
# For details see man 5 crontab
# Example of job definition:
# .—————- minute (0 – 59)
# | .————- hour (0 – 23)
# | | .———- day of month (1 – 31)
# | | | .——- month (1 – 12) January, February, …, December
# | | | | .—- day of week (0 – 7) Sunday, Monday, …, Saturday
# | | | | |
# * * * * * command to be executed
3. 编写Cron表达式
Cron表达式由五个字段组成,分别代表分钟、小时、日、月和星期。以下是一些常见的Cron表达式示例:
每分钟执行一次:
* * * * * command
每小时的第一分钟执行一次:
0 * * * * command
每天的23:59执行一次:
59 23 * * * command
每周星期二的23:59执行一次:
59 23 * * 2 command
高级技巧
1. 使用
@reboot
和
@daily
等特殊命令
Cron提供了一些特殊的命令,用于简化常见任务的设置。
@reboot
:在系统启动时执行一次。
@daily
:每天执行一次。
例如,要在系统启动时执行
/usr/bin/my_script.sh
,可以将以下行添加到
/etc/crontab
文件中:
@reboot /usr/bin/my_script.sh
2. 使用
cronie
扩展
cronie
是Cron的一个扩展,提供了更多的功能,如邮件通知、复杂的日历支持等。你可以通过以下命令安装
cronie
:
sudo apt-get install cronie
3. 使用
crontab -e
编辑用户级别的Cron任务
每个用户都可以使用
crontab -e
命令编辑自己的Cron任务。这对于个人任务或需要特定用户权限的任务非常有用。
4. 使用
crontab -l
查看Cron任务列表
要查看当前用户的Cron任务列表,可以使用以下命令:
crontab -l
5. 使用
crontab -r
删除Cron任务
要删除所有Cron任务,可以使用以下命令:
crontab -r
结论
Cron是Linux系统中强大的定时任务工具,通过本文的介绍,相信你已经掌握了Ubuntu 18.04版Cron的基本使用方法和一些高级技巧。熟练运用Cron可以帮助你自动化日常任务,提高工作效率。