Have you ever wondered how to have a Python script run at a particular time every day while you’re sleeping? Maybe you have a script that needs to extract data from a website every day, or a script that sends an email to someone, or any script that you just want to run automatically periodically.
One way is to use your computer and a program such as Task Scheduler if you are on Windows or cronjob if you are on Mac or Linux. However, this is cumbersome and requires the computer to be up and running 24/7. So, I am not going to talk about that here. There’s a much easier way by using a free web server service such as PythonAnywhere explained below:
PythonAnywhere basically gives you a Linux server with around 500 Mb of disk space where you can run Python, create and store files, etc. Here are the steps to schedule a Python script for execution every day at a certain time:
Your Python file will now be executed every day at the time given by you. If you didn’t have a Python script, and you’re still confused about the benefit of this, here is a basic Python script that you can use to try the above steps:
from datetime import datetime
with open(datetime.now().strftime("%Y-%m-%d-%H-%M-%S"), "w") as myfile:
The above code creates a text file and writes the string “Hi there!” in that text file. The name of the text file will be the current date and time. For example, 2018-02-16-18-20-33.txt which is generated by datetime.now indicating the date and time when the script was executed. So, every time the script is executed, a new text file with a different name is generated. You’re going to have a text file every day.
Once you schedule the task, you can check to see if the file is there by going to your Dashboard and then to Consoles and then click on Bash. That will open the server terminal. That’s the interface that allows you to use your server. There you can create new files, write text in files, change directory, run a Python program, etc.
Once you open the bash, you can simply execute the command:
That will show you a list of files and folders contained in the current directory. Your Python file should be there and the text generated text file should be there too if you followed the steps correctly.
That’s how easy it is to schedule a Python task at a certain time every day.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.