您的位置:首页 > 其它

ubuntu上使用cron执行定时任务计划

2017-07-13 21:54 465 查看
在ubuntu下,cron为自带的系统服务。

任意用户下,输入“crontab -e”即可进入任务编写。相关提示大致如下:

[html] view plain copy print?# 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
# 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
如果是第一次执行“crontab -e”,会提示选择编辑器,选择合适的编辑器即可。我选择的是“4”,vim。

[html] view plain copy print?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]:
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]:


然后,在最后面添加下面内容,然后保存并退出。

[html] view plain copy print?# test 3 * * * * date >>/tmp/test.txt
# test
3 * * * * date >>/tmp/test.txt


至于上面这个表达式的说明,请各看官自行度娘或谷歌。

好了,去看看“/tmp/test.txt”是否有内容吧。

下面是我期间遇到的几个问题。

1.输入“crontab -e”,提示“no
crontab for root - using an empty one”

处理:这个是正常的,提示你,当前设定的用户,没有cron任务。

2.输入“crontab -e”,输入内容后,退出时,提示保存;保存后,任务不能成功添加。

处理:你选择的编辑器有问题。请在root角色下输入“select-editor”,可以重新进行选择。

3.编辑完任务并保存后,重启服务的问题。

有些网文说是“service crond restart”进行服务重启,在这里,需要特别注意的是,在ubuntu下cron服务的重启应该是“service cron
restart ”。注意,是“cron”,而不是“crond”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: