在Ubuntu中,你可以使用at
命令或者cron
来创建计划任务。这些工具允许你根据时间戳(例如,特定的日期和时间)来安排任务的执行。下面是如何使用这两种方法的一些基本指南:
at
命令安装 at
服务 (如果尚未安装):
sudo apt-get update
sudo apt-get install at
启动 at
服务:
sudo systemctl start atd
创建一个计划任务:
使用 at
命令加上你想要执行任务的时间戳。时间戳的格式通常是 HH:MM [date]
,其中 [date]
是可选的,表示具体的日期。
echo "your-command-here" | at 15:30 tomorrow
这个命令会在明天的15:30执行 your-command-here
。
查看待处理任务:
atq
删除待处理任务:
atrm <job-number>
cron
编辑用户的 crontab
文件:
crontab -e
添加一个计划任务:
在打开的编辑器中,你可以按照 cron
的时间格式添加一行来指定任务的执行时间。时间格式如下:
* * * * * command-to-execute
- - - - -
| | | | |
| | | | ----- Day of the week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of the month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
例如,如果你想在每天的15:30执行一个脚本,你可以添加如下行:
30 15 * * * /path/to/your/script.sh
保存并退出编辑器:
保存你的更改并退出编辑器。cron
将自动加载新的计划任务。
查看用户的 crontab
文件:
crontab -l
删除用户的 crontab
文件:
crontab -r
请注意,at
命令通常用于一次性计划任务,而 cron
更适合定期重复的任务。此外,确保你的命令或脚本具有执行权限,并且在 PATH
环境变量中可以找到。