Linux at command with parameters

Команда at в Linux

at — это утилита командной строки, которая позволяет вам планировать выполнение команд в определенное время. Задания, созданные с помощью at , выполняются только один раз.

В этой статье мы расскажем , как использовать at и его компаньоны утилитами batch , atq , atrm просматривать, удалять и создавать новые рабочие места , которые должны выполняться в более позднее время.

Установка at

В зависимости от дистрибутива at может присутствовать или отсутствовать в вашей системе Linux.

Если at не установлен, вы можете легко установить его с помощью диспетчера пакетов вашего дистрибутива.

sudo apt update sudo apt install at

После установки программы убедитесь, что atd , демон планирования запущен и настроен на запуск при загрузке:

sudo systemctl enable --now atd

Как использовать команду at

Упрощенный синтаксис команды at выглядит следующим образом:

Команда at принимает дату и время ( runtime ), когда вы хотите выполнить задание, как параметр командной строки, и команду, которая должна быть выполнена из стандартного ввода.

Создадим задание, которое будет выполнено в 9:00:

Как только вы нажмете Enter , вам будет представлена командная строка at которая чаще всего начинается с at> . Вы также увидите предупреждение о том, в какой оболочке будет выполняться команда:

warning: commands will be executed using /bin/sh at> 

Введите одну или несколько команд, которые хотите выполнить:

tar -xf /home/linuxize/file.tar.gz

Когда вы закончите вводить команды, нажмите Ctrl-D чтобы выйти из подсказки и сохранить задание:

at> job 4 at Tue May 5 09:00:00 2020 

Команда отобразит номер задания, время и дату выполнения.

Есть и другие способы , чтобы пройти команду , которую вы хотите запустить, помимо ввода команды в at строке. Один из способов — использовать echo и направить команду по at :

echo "command_to_be_run" | at 09:00

Другой вариант — использовать здесь документ :

at 09:00 command_to_be_runEND

Чтобы читать команды из файла вместо стандартного ввода, вызовите команду с параметром -f путь к файлу. Например, чтобы создать задание, которое будет запускать скрипт /home/linuxize/script.sh :

at 09:00 -f /home/linuxize/script.sh

По умолчанию, если команда производит вывод, at отправит электронное письмо с выводом пользователю после завершения задания. Invoke at с -M опцией для подавления уведомлений по электронной почте:

Используйте -m чтобы отправить электронное письмо, даже если нет вывода:

batch команда

batch или его псевдоним at -b планирует задания и выполняет их в пакетной очереди, если позволяет уровень загрузки системы. По умолчанию задания выполняются, когда средняя загрузка системы ниже 1,5. Значение нагрузки можно указать при вызове демона atd . Если средняя загрузка системы выше указанной, задания будут ждать в очереди.

Чтобы создать batch задание, передайте команды, которые хотите выполнить:

echo "command_to_be_run" | batch

Указание времени выполнения

Утилита at поддерживает широкий диапазон временных характеристик. Вы можете указать время, дату и приращение от текущего времени:

  • Время — чтобы указать время, используйте форму HH:MM или HHMM . Чтобы указать 12-часовой формат времени, используйте am или pm после времени. Вы также можете использовать такие строки, как now , midnight , noon или teatime (16:00). По истечении указанного времени задание будет выполнено на следующий день.
  • Дата — команда позволяет запланировать выполнение задания на заданную дату. Дату можно указать, используя название месяца, за которым следует день и (необязательно) год. Вы можете использовать строки, например, today , tomorrow или будний день. Дата также может быть указана в MMDD[CC]YY , MM/DD/[CC]YY , DD.MM.[CC]YY или [CC]YY-MM-DD .
  • Increment — at также принимает приращения в формате now + count time-unit , где count — это число, а time-unit может быть одной из следующих строк: minutes , hours , days или weeks .

Время, дату и приращение можно комбинировать, вот несколько примеров:

    Запланируйте работу на ближайшее воскресенье на время на десять минут позже текущего:

Вы также можете указать время и дату в [[CC]YY]MMDDhhmm[.ss] используя параметр -t . Вот пример:

Указание очереди

По умолчанию задания, созданные с помощью at , планируются в очереди с именем a а задания, созданные с помощью batch , планируются в очереди b .

Запросы могут иметь имена от a до z и от A до Z Очереди с меньшими буквами работают с меньшей аккуратностью, что означает, что они имеют приоритет над очереди с более высокими буквами.

Вы можете указать очередь с помощью опции -q . Например, чтобы установить задание в L очередь, вы должны запустить:

Список незавершенных вакансий

Чтобы вывести список ожидающих заданий пользователя, выполните atq или at -l :

В выводе будут перечислены все задания, по одному в каждой строке. Каждая строка включает номер задания, дату, время, букву очереди и имя пользователя.

9 Tue May 5 12:22:00 2020 a linuxize 12 Wed Oct 21 12:30:00 2020 a linuxize 15 Tue May 5 09:00:00 2020 a linuxize 6 Tue May 5 09:00:00 2020 a linuxize 13 Mon May 4 23:08:00 2020 a linuxize 11 Wed Jul 1 10:00:00 2020 a linuxize 4 Tue May 5 09:00:00 2020 a linuxize 

Когда atq вызывается от имени администратора, он перечисляет ожидающие задания всех пользователей.

Удаление незавершенных заданий

Чтобы удалить отложенное задание, atrm команду atrm или at -r после которой atrm номер задания. Например, чтобы удалить задание с номером девять, вы должны запустить:

Ограничение пользователей

/etc/at.deny и /etc/at.allow позволяют контролировать, какие пользователи могут создавать задания с помощью команды at или batch . Файлы состоят из списка имен пользователей, по одному имени пользователя в строке.

По умолчанию существует только файл /etc/at.deny и он пуст, что означает, что все пользователи могут использовать команду at . Если вы хотите отказать в разрешении определенному пользователю, добавьте имя пользователя в этот файл.

Если файл /etc/at.allow существует, только пользователи, перечисленные в этом файле, могут использовать команду at .

Если ни один из файлов не существует, только пользователи с правами администратора могут использовать команду at .

Выводы

Утилита at считывает команды со стандартного ввода и выполняет их позже. В отличие от crontab , задания, созданные с помощью at , выполняются только один раз.

Для получения дополнительной информации обо всех доступных параметрах команды at введите man at в вашем терминале.

Если у вас есть вопросы, не стесняйтесь оставлять комментарии.

Источник

At Command in Linux

In this tutorial, we'll show you how to utilize at and its partner utilities batch, atq, and atrm to view, delete, and create jobs.

At Command in Linux

Introduction

at is a command-line utility that lets you schedule commands to run at a specific time. Jobs that are created with at are only run once.

In this tutorial, we'll show you how to utilize at and its partner utilities batch , atq , and atrm to view, delete, and create jobs that will be run at a later time.

Installing at

at may or may not be present on your Linux system, depending on the distribution.

If at isn't already installed, you can do so using your distribution's package manager.

sudo apt update sudo apt install at 

Make sure that atd , the scheduling daemon is running and set to start on boot after installing the program:

sudo systemctl enable --now atd 

How to Use the at Command

The at command has the following simplified syntax:

As a command-line parameter, the at command accepts the date and time ( runtime ) when you wish to run the task, as well as the command to run from standard input.

Let's create a job that will start at 9:00 a.m.:

When you press Enter, you'll see the at command prompt, which usually begins with at> . There's also a warning that tells you what shell the command will run in:

Output warning: commands will be executed using /bin/sh at> 

Enter one or more commands that you'd want to run:

tar -xf /home/linuxize/file.tar.gz 

Press Ctrl-D to exit the prompt and save the task after you've finished inputting the commands:

Output at> job 4 at Fri Feb 5 09:00:00 2022 

The task number, as well as the execution time and date, will be displayed by the command.

Aside from inputting the command at the prompt, there are additional ways to send the command you want to run. One method is to use echo and pipe the command to the following address:

echo "command_to_be_run" | at 09:00 

Another choice is to use the following document:

Invoke the command with the -f option followed by the path of the file to read commands from a file instead of standard input. To create a job that runs the script /home/vega/script.sh , for example:

at 09:00 -f /home/vega/script.sh 

If the command produces output, by default, at will send the user an email with the output after the operation is finished. To disable the email notification, run at with the -M option:

Even if there is no output, use the -m option to send an email:

batch Command

When the system load level allows, batch or its alias at -b schedules jobs and runs them in a batch queue. The jobs are run by default when the system load average is less than 1.5. When calling the atd daemon, you can specify the load value. Jobs will wait in the queue if the system load average is higher than the specified one.

To create job with batch , enter the commands you want to run:

echo "command_to_be_run" | batch 

Specifying the Execution Time

The at utility can handle a wide range of time constraints. You can set the time, date, and increment from the current time using the following parameters:

  • Time - Use the HH:MM or HHMM format to give a time. Use am or pm after the time to indicate a 12-hour time system. Strings like now, midnight, noon, and teatime can also be used (16:00). If the deadline has gone, the job will be completed the following day.
  • Date - You can use this command to schedule job execution for a specific date. The month name, followed by the day, and an optional year, can be used to specify the date. Strings such as today , tomorrow , or weekday can be used. The date can alternatively be expressed in the following formats: MMDD[CC]YY , MM/DD/[CC]YY , DD.MM.[CC]YY , or [CC]YY-MM-DD .
  • Increment - at also accepts increments in the now + count time-unit style, where count is a number and time-unit might be minutes , hours , days , or weeks .

Here are some instances of how time, date, and increment might be combined:

The -t option can be used to specify a time and date in the [[CC]YY]MMDDhhmm[.ss] . Here's an example:

Specifying Queue

Jobs generated with at are placed in a queue by default, while jobs created with batch are placed in the b queue.

The names of queries might range from a to z and from A to Z . Lower-letter queues have a lower niceness, which means they have priority over queues with higher letters.

The -q option allows you to specify a queue. To place a job in the L queue, for example, type:

Listing Pending Jobs

Run the atq or at -l command to see a list of the user's pending jobs:

All jobs will be listed one by one in the output. The work number, date, time, queue letter, and username are all listed on each line.

Output 9 Tue May 5 12:22:00 2022 a vegastack 12 Wed Oct 21 12:30:00 2022 a vegastack 15 Tue May 5 09:00:00 2022 a vegastack 6 Tue May 5 09:00:00 2022 a vegastack 13 Mon May 4 23:08:00 2022 a vegastack 11 Wed Jul 1 10:00:00 2022 a vegastack 4 Tue May 5 09:00:00 2022 a vegastack 

When atq is run as an administrative user, it displays a list of all users' pending jobs.

Removing Pending Jobs

Use the atrm or at -r command followed by the job number to delete a pending job. To get rid of the work with number nine, for example, run:

Restricting Users

You can regulate which users can create jobs using the at or batch commands using the /etc/at.deny and /etc/at.allow files. The files are made up of a list of usernames, one per line.

Only the /etc/at.deny file exists by default, and it is empty, allowing all users to use the at command. Add the username to this file if you wish to deny permission to a certain user.

Only the users mentioned in the /etc/at.allow file are allowed to use the at command if it exists.

Only users with administrator access can use the at command if none of the files exist.

Conclusion

The at utility takes commands from standard input and waits for them to be executed. Jobs created with at , unlike crontab, are only executed once.

In your terminal, type man at to learn more about all of the at command's options.

If you have any queries, please leave a comment below and we’ll be happy to respond to them.

Источник

Читайте также:  Dns over tls linux
Оцените статью
Adblock
detector