如何在Linux系统上每天运行一次Cron Job


本文将教你如何安排一个cron job,以便每天在特定时间执行脚本、命令或shell脚本。作为系统管理员,我们知道在后台自动运行例行维护作业的重要性。Linux cron实用程序将帮助我们维护这些在后台运行的作业。

Cron Job的通用语法

MIN HOUR Day of month Month Day of Week Command
0-59 0-23 1-31 1-12 0-6 Any Linux command or script

要查看机器上存在的cron作业列表,请运行以下命令:

# crontab -l
no crontab for root

要添加新的cron作业,请运行以下命令:

#crontab -e
no crontab for root - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/ed
2. /bin/nano <---- easiest
3. /usr/bin/vim.basic
4. /usr/bin/vim.tiny
Choose 1-4 [2]:2
# 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

安排特定时间的作业

添加以下示例,以便每天11:00执行指定的日志备份shell脚本。我们可以在字段中指定用逗号分隔的值,这表示需要在所有提到的时间执行脚本。

00 11 * * * /home/backups/scripts/log_backup.sh

结论:配置结束后,你就可以每天在特定时间运行脚本或命令了,像这样,我们可以用逗号分隔的值指定多个执行时间。

更新于:2020年1月20日

5K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告