Run Python Script 24/7 on a Server Automatically – Free

run-python-script-always-in-online-server

So you learned Python and want to do some interesting projects. For some projects, you want your Python script or code to be run 24/7 (always) without manual intervention and without spending anything (free). In this article, I will share my experience of how you can do it with an example.

Why to Run Python Script 24/7 Free?

Let’s say you made a web application (or desktop application), where you want to display some live data. This live data needs to be updated automatically. Now let’s say you are fetching this live data by doing some web scraping or database of a different application.

Let’s take another simple example where you want to update a Google sheet using Python code. Now if you want to update that sheet with the latest data every time, you need to run that Python script 24/7 forever.

In every scenario, you need to run your Python code (or script) all the time (24/7 – 24 hours and 7 days a week). Now you can run any script 24/7 on your local computer. In that case, your local system may crash or you may not have an internet connection for all the time. This is not a good solution.

If you are planning to run your Python code always (24/7) for a long time (say 1 year or 5 years) and you do not want to depend on any free or paid server, then you can buy a Rasberry Pi device and run your code from there.

But in that case, also you need to spend some money to buy that Rasberry Pi device. You can buy it when you think that your code is mature enough to deploy or it will run without any error.

While developing and testing any code you should not use or buy those kinds of devices. Who knows, your application or idea may work or not. In that case, you must look for a free solution to run your Python (or any other language) script 24/7 on a free server.

Prerequisites

To run Python script all the time in a free server for 24 hours, you need:

  • A Python Script
  • A free Replit account
  • A cron job account, which is also free

Steps to Run Python Script 24/7 on Free Server

Okay, let me now show you the entire process of running Python code non-stop on a free online server. I will break the entire process into some steps to explain you better.

Also Read:  How to Write Loops the Pythonic Way

Step1: Create a Python Script

For this example, I will write a sample Python script. Imagine you have an online e-commerce store and lots of customers ordering products from that store. Now you need to update your store database for every order made by a customer. Below is a sample Python code to do that.

import pandas as pd
import time
import random

# Initialize an empty DataFrame
columns = ["Customer ID", "Customer Name", "Customer Address", "Product Name", "Product Price"]
df = pd.DataFrame(columns=columns)

# Function to generate a random row
def generate_random_row():
    customer_id = random.randint(1000, 9999)
    customer_name = f"Customer_{customer_id}"
    customer_address = f"Address_{customer_id}"
    product_name = f"Product_{random.randint(1, 10)}"
    product_price = round(random.uniform(10.0, 100.0), 2)

    return pd.Series([customer_id, customer_name, customer_address, product_name, product_price], index=columns)

# Main loop to add a row and display the DataFrame every minute
while True:
    new_row = generate_random_row()
    df = df.append(new_row, ignore_index=True)
    print("Row added:", new_row)
    print("DataFrame:\n", df)
    
    # Pause for 1 minute
    time.sleep(60)

Output:

Row added: Customer ID                  5296
Customer Name       Customer_5296
Customer Address     Address_5296
Product Name            Product_2
Product Price               59.72
dtype: object
DataFrame:
   Customer ID  Customer Name Customer Address Product Name  Product Price
0        5296  Customer_5296     Address_5296    Product_2          59.72
Row added: Customer ID                  5992
Customer Name       Customer_5992
Customer Address     Address_5992
Product Name            Product_7
Product Price               36.15
dtype: object
DataFrame:
   Customer ID  Customer Name Customer Address Product Name  Product Price
0        5296  Customer_5296     Address_5296    Product_2          59.72
1        5992  Customer_5992     Address_5992    Product_7          36.15
Row added: Customer ID                  5259
Customer Name       Customer_5259
Customer Address     Address_5259
Product Name            Product_7
Product Price               60.53
dtype: object
DataFrame:
   Customer ID  Customer Name Customer Address Product Name  Product Price
0        5296  Customer_5296     Address_5296    Product_2          59.72
1        5992  Customer_5992     Address_5992    Product_7          36.15
2        5259  Customer_5259     Address_5259    Product_7          60.53

In the above Python code, I created a dummy customer data frame with these columns: Customer ID, Customer Name, Customer Address, Product Name, and Product Price. Now I am adding a row with some random value to that dataframe every 1 minute.

As you can see in the above code, I am using a while loop to run that code forever. My intention is to run this Python code in a free online server which needs to be live 24/7 and update the customer database.

Step2: Setting Up Replit Account

Once you log in to your free Replit account, click on + Create Repl (from the top left) then create a Flask replit. While creating Repl, give it a Title name to recognize properly.

create-flask-replit-to-run-python-script-non-stop-24-7-automatically-free-online

Once you create the Flask repl, you will be redirected to a main.py file (if not create a file named main.py). In this main.py remove everything and paste the below code:

Also Read:  5 Best Book for Learning Python
main.py
from flask import Flask
import os

app = Flask(__name__)


@app.route('/')
def home():
  return "I am alive"


if __name__ == "__main__":
  os.system("python script.py &")
  app.run(host="0.0.0.0", port=80)

In the main.py file, you can observe that we are calling a Python script named script.py. This Python script (script.py) is your code, which you want to run 24/7 nonstop. So we need to create another Python file in Replit named script.py.

create-a-python-file-in-replit

In this script.py file, paste the code from Step 1 or you can write your own Python script here which you want to run always in this free online server.

script.py
import pandas as pd
import time
import random

# Initialize an empty DataFrame
columns = ["Customer ID", "Customer Name", "Customer Address", "Product Name", "Product Price"]
df = pd.DataFrame(columns=columns)

# Function to generate a random row
def generate_random_row():
    customer_id = random.randint(1000, 9999)
    customer_name = f"Customer_{customer_id}"
    customer_address = f"Address_{customer_id}"
    product_name = f"Product_{random.randint(1, 10)}"
    product_price = round(random.uniform(10.0, 100.0), 2)

    return pd.Series([customer_id, customer_name, customer_address, product_name, product_price], index=columns)

# Main loop to add a row and display the DataFrame every minute
while True:
    new_row = generate_random_row()
    df = df.append(new_row, ignore_index=True)
    print("Row added:", new_row)
    print("DataFrame:\n", df)
    
    # Pause for 1 minute
    time.sleep(60)

Once you do that, run your code and check if everything is working fine. If everything goes well, you should see a live flask application that will show “I am alive” on the screen.

run-flask-application-in-replit-with-url

Click the New tab button to open this flask application in a new tab of your browser. Once you click that button, you will see a link URL, remember and copy this URL. And don’t stop your Replit application. In my case, the URL was this: https://c429312c-2c20-43b6-b718-1b960221a760-00-zjr95jyj538g.worf.replit.dev/

url-of-your-flask-replit-application

Step3: Configure Cron Job

So our Python script is running on a free Replit cloud server. But one problem is that if you do not open this flask application URL for a certain amount of time, this code will stop executing. Okay, you got the URL. Now to keep your Python script (Flask application) alive for 24/7 non-stop, you need a cron job.

The cron service helps people set up regular tasks on their computer without doing it manually. These tasks could be computer maintenance, data preservation, script execution, or any other automated operation.

To set up a free cron job, go to cron-job.org and sign up there. Now login to your cron job and create a new job.

create-a-cron-job-to-run-python-script-24-7-automatically-example

In the new window, you need to configure your cron job. Here, you just need to give the name of that cron job and the URL you need to monitor. In our case, the flask app URL was created on Replit. In my case, the URL was this: https://c429312c-2c20-43b6-b718-1b960221a760-00-zjr95jyj538g.worf.replit.dev/

One final thing you need to do is configure cron execution timing. For this example, I am selecting the Every 15 minutes configuration. You can change it as per your requirement. That’s it just hit the CREATE button and you are done. Now you can relax and see your code running forever.

configure-cron-job-to-run-run-python-code-automatically

Wrapping Up

In this article, I showed you how you can automate your Python script or code to run it 24/7 for free using Replit and cron job. The code, I used for this example is just a simple one to demonstrate. Maybe you can try some web scraping and update the result in a Google sheet. Later you can embed this Google sheet into your application.

Also Read:  Python Replace all occurrence - Complete Guide

Lastly, I must tell you that there is a drawback in this setup. As per my experience, this code will run continuously for 5 days. After 5 days this code will stop working. In case, you need to again run this Python code from replit and start your cron job. Since everything we are using is free we need to align with that.

Another thing you need to keep in mind is that we are using a free Replit account. So your code will be public. Anyone can view your code. To make your code private in replit, you need to pay some money to them.

That’s it for this article. If you have any questions or suggestions regarding this article, please let me know in the comment section below.

Leave a comment