Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run my python script in the background on a schedule?

I have a small python script that creates a graph of data pulled from MySQL. I'm trying to figure out a way to run the script in the background all time on a regular basis. I've tried a number of things:

  1. A Cron Job that runs the script
  2. A loop timer
  3. Using the & command to run the script in the background

These all have there pluses and minuses:

  1. The Cron Job running more then every half hour seems to eat up more resources then it's worth.
  2. The Loop timer put into the script doesn't actually put the script in the background it just keeps it running.
  3. The Linux & command backgrounds the process but unlike a real Linux service I can't restart/stop it without killing it.

Can someone point me to a way to get the best out of all of these methods?

like image 264
user1441079 Avatar asked Jun 09 '26 06:06

user1441079


1 Answers

Why don't you try to make your script into a proper daemon. This link is a good place to start.

import os
import subprocess
import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/your-pid-name.pid'
        self.pidfile_timeout = 5
    def run(self):

        try:
            while True:

                ### PUT YOUR SCRIPT HERE ###

                time.sleep(300)

        except Exception, e:
            raise

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

You can start/stop/restart this script just like any other linux service.

like image 147
secumind Avatar answered Jun 11 '26 20:06

secumind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!