HOWTO SET-UP A CRONTAB FILE

本文介绍了 Linux 下 Cron 定时任务的基础知识及配置方法。包括 CronTab 文件的创建与编辑、语法示例、如何运行多个命令及禁用邮件通知等。适合初学者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

source: https://corenominal.org/2016/05/12/howto-setup-a-crontab-file/


Foreword: a few days ago, I received an email from Fred with the message:

You used to have an awesome page on crontab. Where’d it go?

The short answer, it got lost when I moved my site to WordPress. Anyhow, prompted by Fred, I thought it might be nice to rescue the content (the page was a good few years old, but still relevant), so I’ve tracked it down and republished it below. I hope someone finds it useful.


In Linux, Cron is a daemon/service that executes shell commands periodically on a given schedule. Cron is driven by a crontab, a configuration file that holds details of what commands are to be run along with a timetable of when to run them.

CREATING A CRONTAB FILE

You can create a crontab file by entering the following terminal command:

crontab -e

Entering the above command will open a terminal editor with a new blank crontab file, or it will open an existing crontab if you already have one. You can now enter the commands to be executed, see syntax below, before saving the file and exiting the editor. As long as your entries were entered correctly your commands should now be executed at the times/dates you specified. You can see a list of active crontab entries by entering the following terminal command:

crontab -l

CRONTAB SYNTAX

A crontab file has six fields for specifying minute, hour, day of month, month, day of week and the command to be run at that interval. See below:

*     *     *     *     *  command to be executed
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- day of week (0 - 6) (Sunday=0)
|     |     |     +------- month (1 - 12)
|     |     +--------- day of month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

CRONTAB EXAMPLES

Writing a crontab file can be a somewhat confusing for first time users, therefore I have listed below some crontab examples:

* * * * *  #Runs every minute
30 * * * *  #Runs at 30 minutes past the hour
45 6 * * *  #Runs at 6:45 am every day
45 18 * * *  #Runs at 6:45 pm every day
00 1 * * 0  #Runs at 1:00 am every Sunday
00 1 * * 7  #Runs at 1:00 am every Sunday
00 1 * * Sun  #Runs at 1:00 am every Sunday
30 8 1 * *  #Runs at 8:30 am on the first day of every month
00 0-23/2 02 07 *  #Runs every other hour on the 2nd of July

As well as the above there are also special strings that can be used:

@reboot  #Runs at boot
@yearly  #Runs once a year [0 0 1 1 *]
@annually  #Runs once a year [0 0 1 1 *]
@monthly  #Runs once a month [0 0 1 * *]
@weekly  #Runs once a week [0 0 * * 0]
@daily  #Runs once a day [0 0 * * *]
@midnight  #Runs once a day [0 0 * * *]
@hourly  #Runs once an hour [0 * * * *]

MULTIPLE COMMANDS

A double-ampersand && can be used to run multiple commands consecutively. The following example would run command_01 and then command_02 once a day:

@daily command_01 && command_02

DISABLING EMAIL NOTIFICATIONS

By default a cron job will send an email to the user account executing the cronjob. If this is not needed put the following command at the end of the cron job line:

>/dev/null 2>&1

Or, you can disable all email notifications by adding the following to the top of the crontab file:

MAILTO=""

SPECIFYING A CRONTAB FILE TO USE

As mentioned at the top of this post, you can create a new crontab file with the “crontab -e” command. However, you may already have a crontab file, if you do you can set it to be used with the following command:

crontab -u  

Therefore the following command…

crontab -u tux ~/crontab

…would set Tux’s crontab file to that of the file named “crontab” residing in Tux’s home directory.

REMOVING A CRONTAB FILE

To remove your crontab file simply enter the following terminal command:

crontab -r

FURTHER INFORMATION

Refer to the man page for further information about crontab. Enter the terminal command:

man crontab

EXTERNAL LINKS

Some external links for your browsing pleasure:

I think that pretty much covers the subject of cron jobs and crontab. Please feel free to comment if I have missed anything or made any obvious mistakes.

Tags:cronlinuxsystem admin

5 COMMENTS

  1. Leslie  says:

    Thank you – for those of us novices at this – I also found this link to be helpful (http://php-opensource-help.blogspot.com/2010/03/how-to-set-up-cron-job-file-using-putty.html). Basically told me how to use the text editor when editing / creating a cronjob – sp[ecifically commands like ‘o’ which puts the user into editing mode, and ZZ which saves the file. Very helpful stuff.

  2. corenominal  says:

    I’m glad you found it useful, and thank you for the link.

  3. Fred  says:

    Thanks for reposting this. Simplicity is king!

  4. rolandjb  says:

    I create my cronjob like this
    30 7 * * * /xxx/xxx/xxx.sh stop
    45 7 * * * /xxx/xxx/xxx.sh start

    The cronjob is successull to stop but unable to start. What happened. Please explain the error cronjob above for linux.

  5. corenominal  says:

    @rolandjb it’s impossible to tell what happened given the information you provided. That said, I’d probably start by looking at the “start” section of your script and adding some basic logging. Also, do you receive any output via email when the job errors?

LEAVE A COMMENT

Your email address will not be published. Required fields are marked *


<think>我们讨论的是在OpenWrt系统中使用crontab来定时执行pppoe重拨脚本。用户提供了crontab的使用帮助信息,并希望了解如何设置定时任务。 根据用户需求,我们需要将pppoe.sh脚本设置为定时任务(比如每10分钟运行一次)。同时,用户可能还希望了解如何确保脚本在系统启动时运行(虽然crontab通常是在系统启动后由crond守护进程读取的,但OpenWrt的crond默认会随系统启动)。 解决方案: 1. 将pppoe.sh脚本保存到OpenWrt设备上(例如/usr/local/bin/pppoe.sh),并赋予可执行权限。 2. 使用crontab -e命令编辑当前用户的crontab文件(在OpenWrt中,通常root用户运行)。 3. 添加一行定时任务,例如:每10分钟运行一次。 注意:在OpenWrt中,cron服务默认可能没有启动,需要安装并启动。 步骤详解: 步骤1:安装cron(如果未安装) 在OpenWrt中,cron通常不是默认安装的,需要先安装: ```bash opkg update opkg install cron /etc/init.d/cron start /etc/init.d/cron enable # 设置开机自启 ``` 步骤2:创建脚本并设置权限 假设脚本路径为/usr/local/bin/pppoe.sh,确保脚本第一行为#!/bin/sh,然后赋予执行权限: ```bash chmod +x /usr/local/bin/pppoe.sh ``` 步骤3:编辑crontab 使用命令`crontab -e`,然后在编辑器中添加: ```cron */10 * * * * /usr/local/bin/pppoe.sh ``` 步骤4:保存并退出(在vi编辑器中,按ESC,然后输入:wq) 步骤5:重启cron服务(可选,一般会自动加载新的crontab) ```bash /etc/init.d/cron restart ``` 但是,用户提供的crontab用法中有一些选项,我们可以解释一下: - `-c DIR`: 指定crontab目录(OpenWrt中通常为/var/spool/cron) - `-u USER`: 指定用户(默认为当前用户) - `-l`: 列出当前用户的crontab - `-e`: 编辑 - `-r`: 删除 - `FILE`: 用文件替换当前crontab(例如:crontab /path/to/file) 因此,除了使用`crontab -e`编辑,还可以通过文件导入: 例如,先创建一个crontab文件(比如mycron),然后运行: ```bash crontab mycron ``` 另外,关于开机自启:由于cron服务本身已经设置为开机自启(通过/etc/init.d/cron enable),所以添加的定时任务在每次重启后都会生效。 但是,用户可能还希望脚本在启动时立即运行一次(而不是等待第一个10分钟周期)。我们可以这样: 在crontab中添加一行,指定在启动时运行(使用@reboot): ```cron @reboot sleep 60 && /usr/local/bin/pppoe.sh # 等待60秒让系统完成启动 */10 * * * * /usr/local/bin/pppoe.sh ``` 注意:OpenWrt的crond是否支持@reboot?我们可以查看crond的版本,一般来说busybox的crond不支持@reboot,而如果安装的是vixie-cron则可能支持。在OpenWrt中,默认安装的是busybox的crond,它不支持@reboot。因此,我们可以通过系统启动脚本来实现。 在OpenWrt中,我们可以将启动脚本放在/etc/rc.local中(在系统启动时执行)。编辑/etc/rc.local,在exit 0之前添加: ```bash # 延迟60秒执行,确保网络服务已经启动 (sleep 60 && /usr/local/bin/pppoe.sh) & ``` 这样,系统启动后60秒,脚本就会运行一次。 完整示例: 1. 编辑/etc/rc.local: ```bash # Put your custom commands here that should be executed once # the system init finished. By default this file does nothing. (sleep 60 && /usr/local/bin/pppoe.sh) & exit 0 ``` 2. 设置crontab(每10分钟运行): ```cron */10 * * * * /usr/local/bin/pppoe.sh ``` 3. 重启cron服务。 这样,我们就实现了: - 系统启动后60秒运行一次脚本 - 之后每10分钟运行一次 注意:如果脚本运行时间较长,需要确保不会重叠执行(例如脚本运行时间超过10分钟),否则可能导致多个实例同时运行。可以在脚本开头使用flock(文件锁)来避免。 在脚本开头添加锁机制: ```bash #!/bin/sh [ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || : ``` 或者更简单的方式(使用一个锁文件): ```bash #!/bin/sh LOCK_FILE="/tmp/pppoe.lock" if ! flock -n 9; then echo "Another instance is running. Exiting." exit 1 fi # 后续脚本内容... exec 9>"$LOCK_FILE" ``` 但是,OpenWrt的busybox可能不包含flock,所以可以使用一个简单的文件锁: ```bash #!/bin/sh LOCK_FILE="/tmp/pppoe.lock" if [ -e "$LOCK_FILE" ]; then if [ -d "/proc/$(cat "$LOCK_FILE")" ]; then echo "Another instance is running. Exiting." exit 1 else # 进程不存在,可能是上次异常退出,删除锁文件 rm -f "$LOCK_FILE" fi fi echo $$ > "$LOCK_FILE" # 脚本主体... # 删除锁文件 rm -f "$LOCK_FILE" ``` 不过,为了简单起见,我们也可以使用单例模式(使用pid文件): 下面是一个更健壮的单例实现: ```bash #!/bin/sh LOCK_FILE="/var/run/pppoe.lock" if [ -f "$LOCK_FILE" ]; then pid=$(cat "$LOCK_FILE") if [ -d "/proc/$pid" ]; then echo "Another instance is running. Exiting." exit 1 else echo "Removing stale lock file." rm -f "$LOCK_FILE" fi fi echo $$ > "$LOCK_FILE" trap 'rm -f "$LOCK_FILE"; exit 0' EXIT # 脚本主体... ``` 这样,我们就确保了同一时间只有一个实例在运行。 因此,完整的pppoe.sh脚本可以这样写(包含锁机制):</think>您提供的输出是关于 `crontab` 命令的使用说明。`crontab` 是 Unix/Linux 系统中用于管理定时任务的工具。下面我将详细解释如何正确使用 `crontab` 来设置定时任务,并提供完整的操作指南。 ### `crontab` 命令详解与使用指南 #### 1. `crontab` 基本语法 ```bash crontab [-c DIR] [-u USER] [-ler] [FILE] ``` #### 2. 参数说明: | 参数 | 说明 | |------|------| | `-c DIR` | 指定 crontab 目录(默认通常是 `/var/spool/cron/crontabs`) | | `-u USER` | 指定用户(默认是当前用户) | | `-l` | 列出当前用户的 crontab 内容 | | `-e` | 编辑当前用户的 crontab | | `-r` | 删除当前用户的 crontab | | `FILE` | 用指定文件替换当前 crontab(`-` 表示从标准输入读取) | #### 3. crontab 时间格式 crontab 的时间格式为: ``` * * * * * command_to_execute ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ │ │ │ │ └── 星期几 (0 - 6) [0 是星期日] │ │ │ └──── 月份 (1 - 12) │ │ └────── 日 (1 - 31) │ └──────── 小时 (0 - 23) └────────── 分钟 (0 - 59) ``` #### 4. 完整使用示例 ##### 示例 1:编辑当前用户的 crontab ```bash crontab -e ``` 这将打开默认编辑器(通常是 vi 或 nano),您可以添加定时任务: ```bash # 每天凌晨 3 点执行备份脚本 0 3 * * * /path/to/backup.sh # 每 10 分钟检查一次网络状态 */10 * * * * /path/to/network_check.sh # 每周一早上 8 点发送报告 0 8 * * 1 /path/to/send_report.sh ``` ##### 示例 2:从文件导入 crontab ```bash # 创建 crontab 文件 echo "0 3 * * * /path/to/backup.sh" > my_crontab echo "*/10 * * * * /path/to/network_check.sh" >> my_crontab # 导入到当前用户 crontab my_crontab ``` ##### 示例 3:从标准输入导入 ```bash echo "0 4 * * * /path/to/cleanup.sh" | crontab - ``` ##### 示例 4:列出当前用户的 crontab ```bash crontab -l ``` 输出示例: ``` 0 3 * * * /path/to/backup.sh */10 * * * * /path/to/network_check.sh 0 8 * * 1 /path/to/send_report.sh ``` ##### 示例 5:删除当前用户的 crontab ```bash crontab -r ``` #### 5. 高级使用技巧 ##### 环境变量设置 ```bash # 在 crontab 顶部设置环境变量 SHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # 设置邮件接收地址 MAILTO="admin@example.com" # 然后添加定时任务 0 3 * * * /path/to/backup.sh ``` ##### 日志重定向 ```bash # 将输出重定向到日志文件 */5 * * * * /path/to/monitor.sh > /var/log/monitor.log 2>&1 # 使用 logger 发送到系统日志 */5 * * * * /path/to/monitor.sh | logger -t my_monitor ``` ##### 特殊时间格式 | 格式 | 含义 | 示例 | |------|------|------| | `@reboot` | 系统启动时运行 | `@reboot /path/to/startup.sh` | | `@yearly` | 每年运行一次 | `@yearly /path/to/yearly_backup.sh` | | `@monthly` | 每月运行一次 | `@monthly /path/to/monthly_report.sh` | | `@weekly` | 每周运行一次 | `@weekly /path/to/weekly_cleanup.sh` | | `@daily` | 每天运行一次 | `@daily /path/to/daily_backup.sh` | | `@hourly` | 每小时运行一次 | `@hourly /path/to/hourly_check.sh` | #### 6. 系统级 crontab 系统级 crontab 文件位于 `/etc/crontab` 和 `/etc/cron.d/` 目录,格式稍有不同: ```bash # /etc/crontab 示例 SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) 47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly ) ``` #### 7. 调试技巧 1. 检查 cron 服务状态: ```bash systemctl status cron ``` 2. 查看系统日志: ```bash grep CRON /var/log/syslog # 或 journalctl -u cron ``` 3. 临时添加任务测试: ```bash # 每分钟执行一次 * * * * * /path/to/test.sh ``` ### 为 PPPoE 脚本设置定时任务 结合之前的 PPPoE 脚本,以下是设置定时任务的示例: ```bash # 创建 crontab 文件 cat > pppoe_cron << EOF # 每 15 分钟检查一次 PPPoE 连接 */15 * * * * /usr/local/bin/pppoe-monitor.sh # 每天凌晨 3 点重启 PPPoE 连接 0 3 * * * /usr/local/bin/pppoe-restart.sh # 系统启动后 2 分钟执行检查 @reboot sleep 120 && /usr/local/bin/pppoe-monitor.sh EOF # 导入到 crontab crontab pppoe_cron # 验证设置 crontab -l ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值