Crontab使用

在Linux终端输入:

crontab -h

可以看到:

usage:  crontab [-u user] file
    crontab [ -u user ] [ -i ] { -e | -l | -r }
        (default operation is replace, per 1003.2)
    -e  (edit user's crontab)
    -l  (list user's crontab)
    -r  (delete user's crontab)
    -i  (prompt before deleting user's crontab)

这里可以通过

crontab -e

对于定时任务进行编辑。
这样就进入到了编辑页面:

# 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

看到最后一行:

分 小时 日 月 星期 命令

输入:

0 * * * * /home/ubuntu/run.sh

表示每小时会执行run.sh
“*”代表取值范围内的数字,
“/”代表”每”,
“-”代表从某个数字到某个数字,
“,”分开几个离散的数字

重启cron服务:

service cron restart

通过相关指令查看进程:

ps -ax | grep cron 

在ubuntu下安装crontab后,系统默认的是不开启crontab的日志记录的,启用crontab的日志的办法:
1.修改rsyslog文件,将/etc/rsyslog.d/50-default.conf 文件中的#cron.*前的#删掉;
重启rsyslog服务service rsyslog restart;
重启cron服务service cron restart;
2.more /var/log/cron.log就可以查看运行时的日志文件,如果在日志文件中出现:No MTA installed, discarding output
那么就是说,crontab执行脚本时是不会直接错误的信息输出,而是会以邮件的形式发送到邮箱里,这时候就需要邮件服务器了,如果没有安装邮件服务器,就会报这个错。如果是测试,可以用下面的办法来解决:
在每条定时脚本后面加入:>/dev/null 2>&1。就可以解决No MTA installed, discarding output的问题。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Linux定时任务Crontab命令详解linux 系统则是由 cron (crond) 这个系统服务来控制的。L...
    时待吾阅读 412评论 0 0
  • crontab是Linux一个定时执行特定任务的程序,网上也有很多使用教程,在这里举一个例子,抛砖引玉。 为了运行...
    蛮三刀酱阅读 890评论 0 1
  • Linux 系统提供了使用者控制计划任务的命令 :crontab 命令。 一、crond简介 crond是linu...
    happeace阅读 1,808评论 0 53
  • Linux定时任务Crontab命令详解 linux 系统则是由 cron (crond) 这个系统服务来控制的。...
    孙燕超阅读 1,840评论 0 4
  • 毕业这么多年,还从来没有给学生买过这么贵重的奖品,不是小气,而是作为房奴的我,压力山大,实在不具备这样的实力。 但...
    西瓜甜甜啦阅读 350评论 22 37