Contents
  1. cron
  2. Rules for Editing Tasks
  3. Configure a Scheduled Task

Certain needs, such as restarting a task at scheduled times, publishing blog updates on a schedule, or regularly backing up files, require certain tasks to be run on a schedule.

cron

cron is a tool for managing and running recurring tasks on Linux systems.

Rules for Editing Tasks

(1) Open the cron task editor

crontab -e

If this is your first time using crontab, the system may ask you to choose a text editor. nano is usually the simpler option.

(2) Configure the cron service

The expression is as follows:

*  *  * *  *   command
分 时 天 月 周   命令
  • Minute: 0-59
  • Hour: 0-23
  • Day: 1-31
  • Month: 1-12
  • Day of the week: 1-6 for Monday through Saturday, and 0 for Sunday

Additionally:

  • *: Represents any value. For example, entering * in the hour field means any hour (every hour).
  • ,: Allows multiple values in one field. For example, entering 1,3 in the minute field means one minute or three minutes.
  • \: Usually used together with *. It represents how often an interval repeats. For example, entering */2 in the hour field means every two minutes. Therefore, */1 and * are equivalent.

For example:

1. \* * * * *      # 每隔一分钟执行一次任务
2. 0 * * * *       # 每小时的0点执行一次任务,比如6:00,10:00  
3. 6,10 * 2 * *    # 每个月2号,每小时的6分和10分执行一次任务  
4. \*/3,\*/5 * * * *   # 每隔3分钟或5分钟执行一次任务,比如10:03,10:05,10:06

Configure a Scheduled Task

(1) Create a script

For example, suppose we need to run the commands hexo g, hexo d in the command line every day.

First, create the script with gedit hexo.sh and enter the following:

#!/bin/bash

HEXO_DIR="/path/hexo_blog_dir"

if [ -d "$HEXO_DIR" ]; then
    cd "$HEXO_DIR" || exit
    hexo g && hexo d
    echo "已在 $HEXO_DIR 执行 hexo g 和 hexo d"
else
    echo "未找到 $HEXO_DIR 目录"
fi

(2) Grant permissions

sudo chmod +x hexo.sh

You can verify whether hexo.sh runs successfully.

(3) Add the scheduled task

Open crontab -e and add the following line:

* 0 * * * /home/mahaofei/Software/everyweek.sh

(4) Restart the cron service

sudo service cron restart

This schedules hexo.sh to run at midnight (hour 0) every day.