Apoorv Ashutosh Apoorv Ashutosh - 11 months ago 47
Python Question

How to have a function exit after 1 hour in Python

I am making a simple app to stream twitter's public timeline, and I want the streaming to stop automatically after an hour, and I have no idea how to do this. I read the datetime and the timeit docs, but cannot understand them. Here is my code, and it is streaming the timeline I want perfectly, but indefinitely.

from twython import TwythonStreamer
import json
import os
import datetime
from datetime import *
class MyStreamer(TwythonStreamer):

def on_success(self, data):
print data['text']
with open('scratch1.json', 'ab') as outfile:
json.dump(data, outfile, indent = 4)
with open('scratch2.json', 'ab') as xoutfile:
json.dump(data, xoutfile, indent = 4)

def on_error(self, status_code, data):
print status_code
return True # Don't kill the stream

def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream

stream = MyStreamer(APP_KEY, APP_SECRET,
stream.statuses.filter(follow = [95995660, 8820362])

Can anyone help me?

Answer Source

Use the datetime.datetime.now() method to get a current datetime object, then use the timedelta class to add an hour to it.

import datetime
stop_time = datetime.datetime.now() + datetime.timedelta(hours=1)

# ...

# in relevant function ...
if datetime.datetime.now() > stop_time:

I'm not familiar with you TwythonStreamer class, but possibly something like this:

class MyStreamer(TwythonStreamer):

    # the init function is called when you create instance of class
    def __init__(self):
        self.stop_time = datetime.datetime.now() + datetime.timedelta(hours=1)

    # ...

    def on_success(self, data):
        if datetime.datetime.now() > self.stop_time:
            raise Exception("Time expired")

        # ...