How to Schedule a Task on a Raspberry Pi?

1. Open the terminal window on your Raspberry Pi.

2. Type in the command “crontab -e” to open the crontab editor.

3. Enter the command you want to run, followed by the time and date you want it to run.

4. Press “Ctrl+X” to save the changes and exit the editor.

5. Your task will now be scheduled to run at the specified time.
[ad_1]

Scheduling commands or scripts on a Raspberry Pi, and on Linux generally, is not easy for a beginner. There are many tips you should know in order to make it work every time, and in this article, you will see the recommendations in detail.

To schedule a task on Raspberry Pi, there is a tool name “crontab”. This tool is useful to run a script at a specific time or on boot.

What is this thing? I will explain it to you.

If you’re looking to quickly progress on Raspberry Pi, you can check out my e-book here. It’s a 30-day challenge where you learn one new thing every day until you become a Raspberry Pi expert. The first third of the book teaches you the basics, but the following chapters include projects you can try on your own.

What is crontab?

Cron

Cron is a service that automatically starts at each boot of the Raspberry Pi and allows the user to execute scheduled commands.

Every minute, cron will watch if it has to do something and do it.
Today, we’ll discuss how to tell cron to execute our commands or scripts when needed.

Crontab

A crontab is a tool that allows us to list what we want to start, in a format that is understandable by the cron service.

A crontab will contain two things:
– the list of commands to run
– when to run them

Crontab is also a command. Here’s the syntax:
crontab [-u user] file
crontab [-u user] [-l | -r | -e] [-i] [-s]

What you need to know:

  • u: crontab is opening the current user crontab by default, but you can specify which one to open (if you have enough privileges).
  • l: list current crontab content.
  • e: edit current crontab content.
  • r: remove current crontab content.

Most of the time, you will only use the commands “crontab -l” or “crontab -e”.

Are you a bit lost in the Linux command line? Check this article first for the most important commands to remember, and a free downloadable cheat sheet so you can have the commands at your fingertips.

Schedule a task on Raspberry Pi

Add a cron

It’s time to take action.

Follow this procedure to schedule a task on your Raspberry Pi:

  • Edit the crontab with the command:
    crontab -e
  • On the first use, you need to choose an editor.
    I advise you to stay on nano, so keep the default choice and hit enter:

    pi@raspberrypi:~ $ crontab -e
    no crontab for pi - using an empty one
    Select an editor. To change later, run 'select-editor'.
    /bin/ed
    /bin/nano <---- easiest
    /usr/bin/vim.tiny
    Choose 1-3 [2]:

  • That’s it. You are now in the editor of crontab, which is empty and can be a little scary if it’s the first time you access it.
    Do not panic. I’ll explain what to do next.
  • All the lines starting with a # are comments and do nothing, so we can ignore them.
    Our changes will be done at the end of the file.
  • Move your cursor to the end of the file, and paste this line:
    * * * * * echo `date` >> /home/pi/log
  • Save the file (CTRL+O and Enter) and exit (Ctrl+X).

This simple line in the crontab will allow us to execute a command every minute, which will write the date in a file. After a few minutes, the file will contain the dates of execution of the command.

You are probably wondering what the five stars mean.

The syntax of an entry in the crontab is as follows:
1 2 3 4 5 command

  • 1: Minute (between 0 and 59)
  • 2: Hour (between 0 and 23)
  • 3: Day (between 1 and 31)
  • 4: Month (between 1 and 12)
  • 5: Day of week (between 0 and 7, starting on Sunday)

Basic example

Now that you understand the theory, let’s look at a simple example to be sure it’s clear.

Imagine that you want to run a backup script every Wednesday at midnight. You must add a line like this:
0 0 * * 3 /home/pi/backup.sh

Midnight for the first two 0s, and 3 for the day of the week (Wednesday).

Other examples

There are then many possibilities to match the crontab with what you need.

  • Launch a script at fixed hours:
    0 6,12 * * * /home/pi/backup.sh
    => will run at 6 and 12 only
  • Start a script every 2h:
    0 */2 * * * /home/pi/backup.sh
    => will run every 2hours (so 0, 2, 4, 6, …)
  • Schedule a script only during the weekdays:
    0 3 * * 1-5 /home/pi/backup.sh
    => will not run on Saturday/Sunday
  • You can also start something on boot:
    @reboot /home/pi/backup.sh
    => will run at every boot

To give you an example, here are some crons I have scheduled on my Pi Zero to control the lights at home:

Adding debug

At the end of the article, we will learn how to debug a cron that does not start or doesn’t start at the time you have planned. But it may be easier to save the displayed messages or script errors in a file.

Let’s say you have a backup scheduled on your Raspberry Pi, here are a few ways to create a log file with debug messages.

To do this, you must add one of these options in the crontab:

  1. To log in to a file what the script would have displayed on the screen if you had launched it manually, you must specify the name of the file with the character “>”:
    @reboot /home/pi/backup.sh > /home/pi/log_backup.txt
    But this option will erase the file at each run.
  2. So if you want to add a new line at the end of the file, you have to add the character “>>”, like this: @reboot /home/pi/backup.sh >> /home/pi/log_backup.txt
  3. Now if you want to log errors in another file you have to add this:
    @reboot /home/pi/backup.sh > /home/pi/log_backup.txt 2>/home/pi/errors_backup.txt
  4. And finally, if you want to save errors and then display them in the same file, you can do this: @reboot /home/pi/backup.sh > /home/pi/log_backup.txt 2>&1

You should be beginning to understand the little tricks by now, but unfortunately in IT things rarely happen as expected. I will give you some tips to fix the errors with the crons on your Raspberry Pi.

Crontab tips

User privileges

A common mistake in creating crons is to forget to consider the privileges of the user who will start the cron.

For example, this cron in the default user of the Raspberry will not work:
@reboot /usr/sbin/service ssh start

You will get an error like this:
Failed to start ssh.service: Interactive authentication required.

If you use the current user’s crontab, the cron will run with your current privileges.
Non administrator users are not allowed to start a service, so it won’t work.

For this to work, you must add this line in the root crontab (sudo crontab -e) or the global crontab found in /etc/crontab.

Related article: How to Easily Log In as Root on Raspberry Pi OS

Absolute path

Another widespread mistake using crons is ignoring the file path. You must use the full path to make it work properly.

This cron will not work, even in the root crontab:
@reboot service ssh start

If you do not specify the absolute path, cron will not know where the service file is. So you must write /usr/sbin/service to make this cron work.

Also, pay attention to the content of your scripts. For example, if you have a PHP script that includes another file (ex: include “file.php”), and you add this script to the crontab, it will not work.

You will need to add the absolute path in the function include or do something like this:
@reboot cd /var/www/html; /usr/bin/php test.php

This way, the include will be done in /var/www/html and the PHP script will find the file “file.php”.

Debugging

In addition to what I wrote above, there are two other methods that I will introduce to debug your crons.

Emails:

Cron will email the user if there is a problem with one of his scheduled tasks in the crontab. If you have a mail server installed on your Raspberry Pi (as explained here), you can check the errors in the email file of your user.

You can easily install one by doing:
sudo apt-get install mailutils

After that, you can type “mail” to read your emails.

If you have a well-configured email server, you can redirect emails to your email address by adding something like this to your crontab:
[email protected]

Syslog :

Syslog is another valuable help to check what happened with your crons.
It’s a log file located in /var/log/syslog.

You can read the last messages about crons with this command:
tail -f /var/log/syslog | grep CRON

It will show you the last errors, with real-time refresh if a new cron starts.

If you are looking for exclusive tutorials, I post a new course each month, available for premium members only. Join the community to get access to all of them right now!

Conclusion

Now you know what a cron and a crontab are, how to schedule a task or a script on Raspberry Pi with many options and how to find out what didn’t work as you want.

Crons are something fundamental in Raspberry Pi and Linux in general. I hope that you understand better how they work, it will serve you very often.

If you have doubts about planning a cron, know that there are websites that allow you either to create your planning or to check if what you did is what you wanted. For example, crontab.guru will do this for you.

Additional Resources

Not sure where to start?
Understand everything about the Raspberry Pi, stop searching for help all the time, and finally enjoy completing your projects.
Watch the Raspberry Pi Bootcamp course now.

Master your Raspberry Pi in 30 days
Don’t want the basic stuff only? If you are looking for the best tips to become an expert on Raspberry Pi, this book is for you. Learn useful Linux skills and practice multiple projects with step-by-step guides.
Download the e-book.

VIP Community
If you just want to hang out with me and other Raspberry Pi fans, you can also join the community. I share exclusive tutorials and behind-the-scenes content there. Premium members can also visit the website without ads.
More details here.

Need help building something with Python?
Create, understand, and improve any Python script for your Raspberry Pi.
Learn the essentials step-by-step without losing time understanding useless concepts.
Get the e-book now.

You can also find all my recommendations for tools and hardware on this page.

[ad_2]

How to Schedule a Task on a Raspberry Pi?

Scheduling tasks on a Raspberry Pi can be a great way to automate processes and save time. Whether you want to run a script at a certain time of day, or you want to set up a cron job to run a task on a regular basis, the Raspberry Pi is a great tool for scheduling tasks. Here’s how to get started.

Step 1: Install Cron

The first step is to install the cron package. This is a tool that allows you to schedule tasks on the Raspberry Pi. To install it, open a terminal window and type:

sudo apt-get install cron

Once the installation is complete, you can move on to the next step.

Step 2: Create a Cron Job

Now that you have cron installed, you can create a cron job. This is a task that will be run at a certain time or on a regular basis. To create a cron job, open a terminal window and type:

crontab -e

This will open an editor window where you can enter the details of your cron job. The syntax for a cron job is as follows:

minute hour day month day-of-week command

For example, if you wanted to run a script at 8am every day, you would enter:

0 8 * * * /path/to/script.sh

Once you have entered the details of your cron job, save the file and exit the editor. Your cron job will now be scheduled to run at the specified time.

Step 3: Test Your Cron Job

Before you can be sure that your cron job is working correctly, you should test it. To do this, open a terminal window and type:

crontab -l

This will list all of the cron jobs that are currently scheduled. If your job is listed, then it is working correctly. If it is not listed, then you may need to check the syntax of your cron job and make sure that it is correct.

Conclusion

Scheduling tasks on a Raspberry Pi is a great way to automate processes and save time. By following the steps outlined above, you can easily set up a cron job to run a task on a regular basis. With a little bit of practice, you can become an expert at scheduling tasks on the Raspberry Pi.

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00