0

This question would be a little silly, but I'm very very new to coding. I could not add the solutions I found on the internet to my codes. I would be so glad if you help.


When I open the .py file, the program does not stop automatically. And it running until I close the command window. After I open this file, I want it to run for 5 minutes and then turn itself off. How can I set a time limit for close the program?

import tweepy
import time


auth = tweepy.OAuthHandler('*','*')
auth.set_access_token('*','*')


api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
user = api.me()

search = 'books'
nrTweets = 500


for tweet in tweepy.Cursor(api.search, search).items(nrTweets):

    try: 
        print('Tweet Liked')
        tweet.favorite()

        time.sleep(10)
    except tweepy.TweepError as e:
        print(e.reason)
    except StopIteration:
        break
  • Is this what you are looking for? [1](https://stackoverflow.com/questions/9812344/cancellable-threading-timer-in-python) and [2](https://stackoverflow.com/questions/14920384/stop-code-after-time-period). Since this is related to threading, I don't think you can precisely stop at exact 5 minutes. – Hung Vu Sep 11 '20 at 01:21
  • @HungVu I guess number 2 is my answer. But, how can I adapt this code to my code? – Alex Miller Sep 11 '20 at 23:10

1 Answers1

0

You can monitor the running time of your program, and break the for-loop after the time limit.

import time

time_limit_sec = 5 * 60
start_time = time.time()

for tweet in tweepy.Cursor(api.search, search).items(nrTweets):
    if (time.time()-start_time) > time_limit_sec:
        break
    ...  # your code here

Shi XiuFeng
  • 715
  • 5
  • 13