How to Schedule a Task on a Raspberry Pi?

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”.

Download Your Essential Linux Commands Guide!
It's a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now

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.

Download Your Essential Linux Commands Guide!
It's a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now
Download Your Essential Linux Commands Guide!
It's a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now

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”.

💰 Make Money Sharing Your Raspberry Pi Expertise!
Help others navigate the world of Raspberry Pi with your insights.
Become a RaspberryTips Contributor!

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:
MAIL=yourname@provider.com

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.

Download Your Essential Linux Commands Guide!
It's a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now

🛠 This tutorial doesn't work anymore? Report the issue here, so that I can update it!

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.

Whenever you’re ready, here are other ways I can help you:

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

Master your Raspberry Pi in 30 days: 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.

The Raspberry Pi Bootcamp: Understand everything about the Raspberry Pi, stop searching for help all the time, and finally enjoy completing your projects.

Master Python on Raspberry Pi: Create, understand, and improve any Python script for your Raspberry Pi. Learn the essentials step-by-step without losing time understanding useless concepts.

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

Similar Posts

2 Comments

  1. Can a crontab entry be set to run an application stored in /bin a certain number of minutes/seconds after boot?

    Actually want it to run AFTER network has been established AND the Pi has updated its real time

    1. Hi Neil,

      I don’t know if there is a better way to do this, but you can run two commands in a cron, so you can add a timer before the main command.
      Example: @reboot sleep 60;/bin/yourapp

      I hope it won’t wait to complete the boot, if it’s the case try another solution given on my article on how to auto start a program on boot.

Comments are closed.