当前位置: 首页>>技术教程>>正文


在Linux上,如何使用at命令安排任务

, ,
了解如何使用at程序安排和管理任务

要求

  • 根权限启动atd守护程序
  • 安装了at程序

困难

简单

约定

  • -要求linux命令可以直接以root用户身份或通过使用root特权以root特权执行sudo命令
  • $-要求linux命令以普通非特权用户身份执行

介绍

在系统管理期间,能够安排任务以供日后执行是一项关键功能:例如执行数据库备份,或者可能运行维护脚本。鲜为人知cron要么anacronat程序使我们能够以一种非常简单的方式执行此操作:在本教程中,我们将学习如何使用它以及它与上述程序的不同之处。

什么事啊

与cron不同,它可以让我们定期运行任务,at使我们能够在指定的日期和时间或在给定的时间间隔后执行命令或脚本。分钟,小时,天或周可以用作单位。甚至可以使用某些”keywords”作为midnight要么teatime(相当于下午4点)。




安装在

如果默认情况下未安装,at应该在几乎所有发行版的存储库中都可用。

要将其安装在Fedora上,只需运行:

# dnf install at

在RHEL或CentOS上,yum仍然是默认的软件包管理器:

# yum install at

在Debian或Ubuntu上:

# apt-get install at

在Archlinux上:

# pacman -S at

启动守护程序

程序安装完成后,我们必须启动atd守护程序并最终启用它,如果我们希望它在引导时自动启动。我在这里假设使用systemd作为初始化系统。该命令必须以root特权执行:

# systemctl enable --now atd.service

在提示符下安排作业

一切就绪后,我们现在可以使用at。假设我们要从现在开始1分钟运行一条命令。正确的语法为:

$ at now + 1 minute

要从现在起三天下午4点运行相同的命令,我们将运行:

$ at 4pm + 3 days

执行以上代码后,at将出现提示,等待我们在指定的时间间隔后输入要执行的命令:




$ at now + 1 minutes
at> echo "Hello world" > test.txt
at> 
job 4 at Tue Dec 19 11:29:00 2017

退出at提示我们应该按CTRL+d组合键。在这一点上,我们将提供计划任务的摘要,该摘要将向我们展示job id(在这种情况下为4)以及执行日期。

举个例子,我们输入了一个简单的命令来说明at作品。一分钟后,”Hello world”字符串将被写入文件test.txt,如果尚不存在,该文件将自动创建。

安排脚本执行

我们可以从提示中指定交互地执行命令,而不是指定要交互地执行的命令。at只需通过将现有脚本或程序作为参数传递给-f标记,或者使用 redirection operator. Therefore, assuming we want to run a script which is present in our current working directory, we would run:


# Using the dedicated -f flag
$ at now + 1 minute -f script.sh

# Using the

Manage scheduled jobs

To queue, examine or delete jobs scheduled with at, we can either use dedicated commands like atrm and atq or run at with specific flags, the latter being just aliases for the former. For example, say we want to obtain a list of all pending jobs scheduled with at by our user:

 $ atq
4      Tue Dec 19 11:29:00 2017 a egdoc

The above command, if launched as root, will display the task scheduled by all users in the system.

To delete a queued job, we could use atrm or run at with the equivalent flags: -r or -d. The job to be deleted must be referenced by its number. In the case above, we would therefore run:

 $ atrm 4 

Conclusions

Although simpler than cron or anacron, the at program can be very useful in certain situations: to run a program with a specific delay or when you know exactly the time in which the task must be executed. Reference the manual for further information, and add this little tool to your toolbox, it will surely come in handy.

参考资料

本文由Ubuntu问答整理, 博文地址: https://ubuntuqa.com/article/10472.html,未经允许,请勿转载。