在ubuntu下,cron为自带的系统服务。
第一种设置计划任务的方式是
任意用户下,输入“crontab -e”即可进入任务编写
如果需要给root账户设置计划任务,可以使用sudo crontab -e或者sudo -s切换回root用户再用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
如果是第一次执行“crontab -e”,会提示选择编辑器,选择合适的编辑器即可。我选择的是“4”,vim。
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]:
然后,在最后面添加下面内容,然后保存并退出
* * * * * ~/test.sh
test.sh内容为,记得给755执行权限 sudo chmod +x ~/test.sh
#!/bin/bash echo "Now time is `date` !" >> ~/time.log
最后我们重启下计划任务服务
service cron restart
tail -f查看time.log的内容
Now time is 2018年 08月 22日 星期三 19:54:01 CST ! Now time is 2018年 08月 22日 星期三 19:55:01 CST ! Now time is 2018年 08月 22日 星期三 19:56:01 CST !
看到不断有新的写入,那就是成功了
第二种配置是在/var/spool/cron/crontabs下创建一个当前用户的文件
例如当前ubuntu登录账户为merci
那么就是
vi /var/spool/cron/crontabs/merci #添加内容 * * * * * ~/test.sh
然后重启计划任务
service cron restart