Schedule tasks in linux

11 Cron Command Examples in Linux [Schedule Cron Jobs]

In this article, we are going to review and see how we can schedule and run Linux tasks in the background automatically at regular intervals using the Crontab command.

Dealing with a frequent job manually is a daunting task for system administrators and such tasks can be scheduled and run automatically in the background without human intervention using cron daemon in Linux or Unix-like operating system.

You might also like:

For instance, you can automate Linux system backup, schedule updates, and synchronization of files, and many more using Cron daemon, which is used to run scheduled tasks from the command line or use online tools to generate cron jobs.

Cron wakes up every minute and checks scheduled tasks in countable – Crontab (CRON TABle) is a table where we can schedule such kinds of repeated tasks.

Tips: Each user can have their own crontab to create, modify and delete tasks. By default cron is enabled for users, however, we can restrict users by adding an entry in /etc/cron.deny file.

Crontab in Linux

The Crontab file consists of commands per line and has six fields actually and separated either by space or tab. The beginning five fields represent the time to run tasks and the last field is for command.

  • Minute (hold values between 0-59)
  • Hour (hold values between 0-23)
  • Day of Month (hold values between 1-31)
  • The month of the year (hold values between 1-12 or Jan-Dec, you can use the first three letters of each month’s name i.e Jan or Jun.)
  • Day of week (hold values between 0-6 or Sun-Sat, Here also you can use the first three letters of each day’s name i.e Sun or Wed. )
  • Command – The /path/to/command or script you want to schedule.

1. List Crontab Entries

List or manage the task with the crontab command with -l option for the current user.

# crontab -l 00 10 * * * /bin/ls >/ls.txt

2. Edit Crontab Entries

To edit the crontab entry, use -e the option shown below. The below example will open scheduled jobs in the VI editor. Make necessary changes and quit pressing :wq keys that save the setting automatically.

Читайте также:  Mounting vmware shared folders linux

3. List Scheduled Cron Jobs of User

To list scheduled jobs of a particular user called tecmint using the option as -u (User) and -l (List).

# crontab -u tecmint -l no crontab for tecmint

Note: Only root user have complete privileges to see other users’ crontab entries. Normal users can’t view others.

4. Remove Crontab Entry

Caution: Crontab with -r the parameter will remove complete scheduled jobs without confirmation from Crontab. Use -i option before deleting the user’s crontab.

5. Prompt Before Deleting Crontab

crontab with -i the option will prompt you confirmation from the user before deleting the user’s crontab.

# crontab -i -r crontab: really delete root's crontab?

6. Allowed Special Characters (*, -, /, ?, #)

  • Asterisk(*) – Match all values in the field or any possible value.
  • Hyphen(-) – To define a range.
  • Slash (/) – 1st field /10 meaning every ten minutes or increment of range.
  • The Comma (,) – To separate items.

7. System-Wide Cron Schedule

A system administrator can use the predefined cron directory as shown below.

  • /etc/cron.d
  • /etc/cron.daily
  • /etc/cron.hourly
  • /etc/cron.monthly
  • /etc/cron.weekly

8. Schedule a Job for a Specific Time

The below jobs delete empty files and directories from /tmp at 12:30 am daily. You need to mention the user name to perform the crontab command. In the below example, root user is performing a cron job.

# crontab -e 30 0 * * * root find /tmp -type f -empty -delete

9. Special Strings for Common Schedule

Strings Meanings
@reboot The command will run when the system reboots.
@daily Once per day or may use @midnight.
@weekly Once per week.
@yearly Once per year. we can use the @annually keyword also.

Need to replace five fields of the cron command with keywords if you want to use the same.

10. Multiple Commands with Double ampersand(&&)

In the below example, command1 and command2 run daily.

# crontab -e @daily &&

11. Disable Email Notifications.

By default, cron sends mail to the user account executing cronjob. If you want to disable it add your cron job similar to the below example. Using the >/dev/null 2>&1 option at the end of the file will redirect all the output of the cron results under /dev/null.

[[email protected] ~]# crontab -e * * * * * >/dev/null 2>&1

conclusion: Automation of tasks may help us to perform our tasks in better ways, error-free, and efficient. You may refer to a manual page of crontab for more information by typing the ‘man crontab‘ command in your terminal.

Источник

How to schedule tasks using the Linux ‘at’ command

Man wearing a wristwatch

Time is precious, making time management an appreciated virtue in every aspect of life, whether you’re talking about financials, technology, or any other daily activity.

Читайте также:  Linux выключить компьютер консоли

To manage time, a skilled sysadmin must know when and how to control tasks so that they can be programmatically executed at certain times, whether recurring or a set number of times. You can apply this concept in numerous scenarios, from scheduled backup tasks to collecting system logs periodically.

[ Keep your most commonly used commands handy with the Linux commands cheat sheet. ]

You can accomplish task scheduling in numerous ways. In this article, I focus on a straightforward tool available on Linux operating systems to help achieve this goal: the at command. My colleague Seth previously wrote a great article about at , so I recommend you check it out, as well as my article about the cron command, another Linux scheduling tool.

This article aims to be as brief, straightforward, and practical as possible, meaning I won’t be able to explore all available options for the at utility. Let’s get started!

Install the ‘at’ utility

Depending on your Linux distribution, the at utility may or may not be installed by default. You can install it using your distribution’s package manager if it’s not installed. For Red Hat Enterprise Linux (RHEL)-based distributions:

The at package installs other binaries that are used together with the main command:

$ sudo dnf repoquery -l at | grep bin [. ] /usr/bin/at /usr/bin/atq /usr/bin/atrm /usr/bin/batch /usr/sbin/atd /usr/sbin/atrun

The package provides the atd daemon, which you’ll interact with through the use of the at and atq commands:

$ sudo systemctl status atd ● atd.service - Job spooling tools Loaded: loaded (/usr/lib/systemd/system/atd.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2022-11-09 17:47:48 -03; 14min ago Main PID: 1378 (atd) Tasks: 1 (limit: 23643) Memory: 428.0K CGroup: /system.slice/atd.service └─1378 /usr/sbin/atd -f nov 09 17:47:48 demo.example.local systemd[1]: Started Job spooling tools.

Training & certification

When to use the ‘at’ utility

The at and batch ( at -b ) commands read from standard input or a specified file. The at tool allows you to specify that a command will run at a particular time. The batch command will execute commands when the system load levels drop to a specific point. Both commands use the user’s shell.

Install the at package if you need a utility for time-oriented job control. If you have a recurring job that repeats at the same time every day, week, and so forth, use crontab instead.

For more detailed information on all the possible parameters and examples of how to use at , read the man page:

Schedule tasks with the ‘at’ command

I’ll show you how at works. First, I’ll establish the time frame:

$ date fri nov 11 15:21:58 -03 2022

Now, there are some different ways to interact with the at utility. One of them is using its interactive command prompt. Do this by typing at and pressing Enter:

$ date fri nov 11 15:26:21 -03 2022 $ at 15:27 warning: commands will be executed using /bin/sh at> echo "It works!" > /tmp/test.txt at> job 2 at Fri Nov 11 15:27:00 2022

I defined a command to run at 15:27 (3:27 pm GMT-3) after defining my runtime and entering the at command prompt. In this case, the command creates a text file. To exit the command prompt, type Ctrl+D. The at utility then queues the command to execute later, according to the runtime definition. For an overview of the pending jobs for the current user, use the atq or at -l commands:

$ atq 2 Fri Nov 11 15:27:00 2022 a localuser

From the previous output, you can see the following:

  • 2 is the unique job number.
  • Fri Nov 11 15:27:00 2022 is the execution date and time for the scheduled job.
  • a indicates that the job is scheduled with the default queue a.
  • localuser is the job owner (and the user the job runs as).
Читайте также:  Create bin file linux

[ Want to test your sysadmin skills? Take a skills assessment today. ]

After waiting for 39 seconds, here’s what happens when the job gets out of the queue and executes:

$ date fri nov 11 15:27:01 -03 2022 $ atq $ cat /tmp/test.txt It works!

Of course, this is not an ideal way of running scheduled jobs; another way is by pipelining the desired command as an input for the at utility. Learn more about that in my article about manipulating files with shell redirection and pipelines. Here is a quick example:

$ rm /tmp/test.txt $ echo "It works while pipelining!" > /tmp/test.txt | at 15:41 warning: commands will be executed using /bin/sh job 3 at Fri Nov 11 15:41:00 2022 $ atq 3 Fri Nov 11 15:41:00 2022 a localuser $ date fri nov 11 15:40:40 -03 2022 $ atq $ date fri nov 11 15:41:01 -03 2022 $ cat /tmp/test.txt It works while pipelining!

Use flags with the ‘at’ command

The most used form of the at utility is specifying an existing script with the -f parameter (or using shell redirection like at so that at can read the inputs from a file instead of a standard input. Check it out:

$ rm /tmp/test.txt $ cat myscript.sh > echo "It works while scripting!" > /tmp/test.txt > EOF $ ls myscript.sh $ sudo chmod +x myscript.sh $ date fri nov 11 15:50:58 -03 2022 $ at 15:52 -f ./myscript.sh warning: commands will be executed using /bin/sh job 4 at Fri Nov 11 15:52:00 2022 $ atq 4 Fri Nov 11 15:52:00 2022 a localuser $ date fri nov 11 15:52:00 -03 2022 $ atq $ cat /tmp/test.txt It works while scripting!

Источник

Оцените статью
Adblock
detector