Section 53.1: 在指定时间执行一次任务

注意:大多数现代发行版默认不安装 at。

要在现在之外的其他时间执行一次作业,如本例中的下午 5点,可以使用

echo "somecommand &" | at 5pm

如果您想捕捉输出结果,可以通过常规方法实现:

echo "somecommand > out.txt 2>err.txt &" | at 5pm

下面这么多的时间格式,所以你也可以写

echo "somecommand &" | at now + 2 minutes
echo "somecommand &" | at 17:00
echo "somecommand &" | at 17:00 Jul 7
echo "somecommand &" | at 4pm 12.03.17

如果没有给出年份或日期,它将假定您指定的时间在下一次出现。因此,如果您给出的小时已经过了今天,它就会假定是明天;如果您给出的月份已经过了今年,它就会假定是明年。

它还可以与 nohup 配合使用。

echo "nohup somecommand > out.txt 2>err.txt &" | at 5pm

还有一些命令可以控制定时作业:

  • atq 列出所有定时任务(atqueue)

  • atrm 删除定时作业(atremove)

  • batch 的功能与 at 基本相同,但只在系统负载低于 0.8 时运行作业。

所有命令都适用于登录用户的作业。如果以根用户身份登录,当然会处理系统范围内的作业。

Section 53.2: 使用 systemd.timer 在指定时间重复执行作业

systemd 提供了 “cron ”的现代实现。要定期执行脚本,需要一个服务和一个定时器文件。服务文件和定时器文件应放在 /etc/systemd/{system,user}中。服务文件

[Unit]
Description=my script or programm does the very best and this is the description

[Service]
# type is important!
Type=simple
# program|script to call. Always use absolute pathes
# and redirect STDIN and STDERR as there is no terminal while being executed
ExecStart=/absolute/path/to/someCommand >>/path/to/output 2>/path/to/STDERRoutput
#NO install section!!!! Is handled by the timer facitlities itself.
#[Install]
#WantedBy=multi-user.target

接下来是计时器文件:

[Unit]
Description=my very first systemd timer
[Timer]
# Syntax for date/time specifications is Y-m-d H:M:S
# a * means "each", and a comma separated list of items can be given too
# *-*-* *,15,30,45:00 says every year, every month, every day, each hour,
# at minute 15,30,45 and zero seconds

OnCalendar=*-*-* *:01:00
# this one runs each hour at one minute zero second e.g. 13:01:00