r_dub_
r_dub_

Reputation: 41

How to sleep my python script every hour

I want to pause my code every hour mark, i.e 11:00pm, 12:00am, 1:00am, etc.

How do I go about doing this?

Upvotes: 1

Views: 12597

Answers (1)

user1529891
user1529891

Reputation:

You have two ways to do this:

cron method

Add a cron job for your script that gets executed every hour:

@hourly python /path/to/script

code method

Create an infinite loop within your code that runs every hour (have it sleep for 60 minutes). Or, create an infinite loop within your code that sleeps every minute, have it periodically check what time it is, and if it's on the hour with different delta hour than the current hour, have it run the job.

import datetime
import time

delta_hour = 0

while:
    now_hour = datetime.datetime.now().hour

    if delta_hour != now_hour:
        # run your code

    delta_hour = now_hour

    time.sleep(60) # 60 seconds

    # add some way to exit the infinite loop

Upvotes: 6

Related Questions