Gautam
Gautam

Reputation: 255

Restart python script if not running/stopped/error with simple cron job

Summary: I have a python script which collects tweets using Twitter API and i have postgreSQL database in the backend which collects all the streamed tweets. I have custom code which overcomes the ratelimit issue and i made it to run 24/7 for months.

Issue: Sometimes streaming breaks and sleeps for given secs but it is not helpful. I do not want to check it manually.

def on_error(self,status)://tweepy method
    self.mailMeIfError(['me <me@localhost'],'listen.py <root@localhost>','Error Occured on_error method',str(error))
    time.sleep(300)
    return True

Assume mailMeIfError is a method which takes care of sending me a mail.

I want a simple cron script which always checks the process and restart the python script if not running/error/breaks. I have gone through some answers from stackoverflow where they have used Process ID. In my case process ID still exists because this script sleeps if Error.

Thanks in advance.

Upvotes: 1

Views: 1607

Answers (2)

Nanda
Nanda

Reputation: 173

Using Process ID is much easier and safer. Try using watchdog.

Upvotes: 2

Martin Evans
Martin Evans

Reputation: 46779

This can all be done in your one script. Cron would need to be configured to start your script periodically, say every minute. The start of your script then just needs to determine if it is the only copy of itself running on the machine. If it spots that another copy is running, it just silently terminates. Else it continues to run.

This behaviour is called a Singleton pattern. There are a number of ways to achieve this for example Python: single instance of program

Upvotes: 2

Related Questions