'Does Heroku 'redeploy' or 'reruns' applications if they break?

I’ve created a Python script that all it does is run some logic 1x every 24 hours, modifies a .txt file and send out a tweet. However, it seems the script is getting redeployed as it’ll resend the message that’s outside the while loop (which is supposed to be infinite) a few times a day.

I suspect it might be because my script goes into the Exception? But I haven’t run into that error at all while testing.

This is what the script looks like:

import tweepy

env_path = Path(‘.’) / ‘.env’
load_dotenv(dotenv_path=env_path)

SLEEP_TIME = 86400  # 1 day, in seconds

def send_tweet(message):
  tweet(message)

def read_last_tweet_id(file_name):
    file_read = open(file_name, ‘r’)
    last_tweet_id = file_read.read()
    file_read.close()
    return last_tweet_id

def store_last_tweet_id(file_name, last_tweet_id):
    file_write = open(file_name, ‘w’)
    file_write.write(last_tweet_id)
    file_write.close()
    return

def tweet_on_mondays():

    last_tweet_id = read_last_tweet_id(LAST_TWEET_FILE)

    while True:

        if date.today().weekday() == 0:  # It’s Monday

            try:
                new_tweet_id = last_tweet_id + 1
                send_tweet(‘It’s Monday dudes’)
                last_tweet_id = new_tweet_id
                store_last_tweet_id(last_tweet_id)

            except Exception as ex:

                print(‘EXCEPTION >>>’, ex)
        else:
            print(‘not a Monday, not sending tweet out’)

        time.sleep(SLEEP_TIME)

tweet(“I should only run once, as it goes into a while loop afterwards”)
tweet_on_mondays()

Also is there a place on Heroku I can verify whether my application crashed and got redeployed?



Solution 1:[1]

all it does is run some logic 1x every 24 hours, modifies a .txt file and send out a tweet

The "1x every 24 hours" part of this should not be part of your application.

Rewrite your script to just do the logic, modify the .txt file, and send out a tweet. Then deploy as a worker, e.g. by creating a Procfile like this:

worker: python path/to/your/script.py

Scale your worker dynos down to zero so this doesn't run all the time:

heroku ps:scale worker=0

And schedule the script to run using Heroku Scheduler:

  1. Provision the addon with heroku addons:create scheduler:standard
  2. Open the scheduler with heroku addons:open scheduler
  3. Add a task with the right frequency and enter worker as the command

You can use a different name for your command if you wish. Just make sure to change both the Procfile and the sheduled job to use the same name. Anything other than web or release is fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris