Quantcast
Channel: Hasen Judy
Viewing all articles
Browse latest Browse all 50

setTimeout for python

$
0
0

In Javascript, there’s a function you can call to execute some function in the future:

setTimeout(fn, delayMillis)

This will call fn() after delayMillis milliseconds.

To get a similar functionality in python, we need first to install a package apscheduler, then we can implement a similar functionality like this:

from apscheduler.scheduler import Scheduler
import datetime as dt

sched = Scheduler()
sched.start()

def timeout(job_fn, *fn_args, **delta_args):
    """Like setTimeout in javascript; returns a job object

    First argument is the function to be called.

    Positional arguments will be passed to the function when it's called.

    Keyword arguemnts will be passed to datetime.timedelta

    Usage:
        # calls `fn()` after 3 seconds
        timeout(fn, seconds=3)

        # calls `fn(foo, bar)` after 10 seconds
        timeout(fn, foor, bar, seconds=10)
    """
    time = dt.datetime.now() + dt.timedelta(**delta_args)
    return sched.add_date_job(job_fn, time, fn_args)

Here, the function timeout works sort of like setTimeout, but the delay must be specified using keyword arguments; it accepts the same things that are accepted by datetime.timedelta

For instance:

def hello(): print "Hello"

timeout(hello, seconds=4)

The thing about this though, is you have to keep the program from quitting. Unlike node.js, the python script will quit when it reaches the end of the script, even if you have scheduled delayed functions.

If you are running a web server, you don’t need to do anything as the web server will continue running for ever (listening for incoming connections).

Otherwise, you need to somehow block or sleep.

The simplest way to do that is time.sleep

Simplest example:

Here’s a simple example.

def hello_spam(): 
    print "Hello"
    timeout(hello_spam, seconds=3)

hello_spam()

import time
time.sleep(10)

This will print “Hello” about four times and then die.

Additional arguments

You can also pass additional arguments to the function you want to call.

Example:

def hello_spam(name): 
    print "Hello {0}".format(name)
    timeout(hello_spam, name, seconds=1)

hello_spam("Dude")

Positional arguments to timeout are going to be passed to the function you’re delaying.

Notice that this means if you do this: timeout(fn, 2000) expecting that you’ll call fn after 2 seconds, you would be making a mistake. You’re telling timeout to call fn(2000) but you’re not telling when you want that call to happen. It will freak out and raise an exception.

Here’s the demo file on a gist: https://gist.github.com/hasenj/5352608


Viewing all articles
Browse latest Browse all 50

Trending Articles