Skip to content

Instantly share code, notes, and snippets.

@wbchn
Created May 11, 2016 06:16
Show Gist options
  • Save wbchn/42268c98ac0048079b9016d4be9eb506 to your computer and use it in GitHub Desktop.
Save wbchn/42268c98ac0048079b9016d4be9eb506 to your computer and use it in GitHub Desktop.
Python Timer for WEB

web framework

Base on Timer

import time
from threading import Timer

def on_time_handler(order_id=None, notify_url=None):
    """
    https://docs.python.org/2/library/threading.html#threading.Timer
    """
    # put data to rq queue will be a good choice.
    # q.enqueue(notify_func, (order_id, notify_url)))   
    print 'On Time Handler: ', time.ctime(), order_id, notify_url
    return 

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/delay/<order_id>')
@app.route('/delay/<order_id>/<int:delay_time>')
def order_delay(order_id, delay_time=10):
    now = time.time()
    Timer(delay_time, on_time_handler, (order_id, '11111aaaa')).start()
    print 'put order: {}, will run at {}'.format(order_id, time.ctime(now+delay_time))
    return 'Add {}, notify at {}'.format(order_id, time.ctime(now+delay_time))

if __name__ == '__main__':
    app.run(debug=True)

Test

curl http://127.0.0.1:5000/delay/100
curl http://127.0.0.1:5000/delay/100
curl http://127.0.0.1:5000/delay/100

or

curl http://127.0.0.1:5000/delay/100/1
curl http://127.0.0.1:5000/delay/100/1
@wbchn
Copy link
Author

wbchn commented May 11, 2016

Test Result

... other get request logs ...
put order: 100, will run at Wed May 11 13:42:19 2016
127.0.0.1 - - [11/May/2016 13:42:18] "GET /delay/100/1 HTTP/1.1" 200 -
On Time Handler:  Wed May 11 13:42:18 2016 100 11111aaaa
put order: 100, will run at Wed May 11 13:42:20 2016
127.0.0.1 - - [11/May/2016 13:42:19] "GET /delay/100/1 HTTP/1.1" 200 -
On Time Handler:  Wed May 11 13:42:19 2016 100 11111aaaa
put order: 100, will run at Wed May 11 13:42:20 2016
127.0.0.1 - - [11/May/2016 13:42:19] "GET /delay/100/1 HTTP/1.1" 200 -
On Time Handler:  Wed May 11 13:42:19 2016 100 11111aaaa
On Time Handler:  Wed May 11 13:42:19 2016 100 11111aaaa
On Time Handler:  Wed May 11 13:42:19 2016 100 11111aaaa
On Time Handler:  Wed May 11 13:42:19 2016 100 11111aaaa
On Time Handler:  Wed May 11 13:42:19 2016 100 11111aaaa
On Time Handler:  Wed May 11 13:42:20 2016 100 11111aaaa
On Time Handler:  Wed May 11 13:42:20 2016 100 11111aaaa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment