

We learn to run a Python script at the right time automatically using bash and crontab.
We continue to write a robot that analyzes government contracts. Today we will figure out how to teach the script to run independently, without your participation - you will only specify the required time.
We will need bash and crontab , let's start with the first one. Bash has a specific language that we can use in the terminal. First you need to create a file that bash can interact with, that is, run it and execute its commands.
Let's open the project and create a new file runscript.sh . It should always start with the line #!/bin/bash .

After this, we can write a command for execution, it will work like any of our previous commands in the terminal: we will write python3 and the name of the file that needs to be run. After that, in the terminal we write the bash command and the name of our script.


When the command is completed, a letter with government contracts should be sent to your email. We also need to activate the environment in which we worked when we wrote our project. Let's add another line to the script with the source command and a link - you can see it when you launch the virtual environment.

What we did now was still manual work. Let's figure out how to automate it - crontab is useful for this. We return to the terminal and use the crontab -l command to check whether there are any crontabs already running. In our case there shouldn't be any.

To create a crontab, enter crontab -e and get into the vi program, where we can write it. The site crontab guru will help us with this. Using asterisks and numbers, we can specify how often we want to run the script. Five stars means that the script will be executed every minute.

If, for example, we specify 0 in minutes and 21 in hours, then the code will be executed every day at 9 pm.

For example, let's try to run the script every minute. To start writing something in vi , you must first press the letter i. Now let's write down the parameters for crontab (in our case * * * * * ) and add bash runscript.sh at the end. To finish editing the vi file, press the Esc key and write :wq .

Let's check whether it appears in the list with the command crontab -l , already known to us.

To monitor mailings, use the mail command in the terminal. It will show whether you received letters and how many.

Now it's time to stop the script. To do this, let's write crontab -r . You can double-check it with the same command crontab -l .
Using crontab, you can run not only Python scripts, but also some other processes - but for this the computer must be turned on. Next time we’ll figure out how to do the same thing, but on a remote server, so that the script’s operation is not tied to your computer.
If you have any questions, you can ask them in our Telegram chat .
Support those