Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a certain function for a specific time in Python?

For example i have function do_something() and I want it to run for exactly 1 second (and not .923 seconds. It won't do. However 0.999 is acceptable.)

However it is very very important that the do_something must exactly run for 1 second. I was thinking of using UNIX time stamp and calculate the seconds. But I am really wondering if Python has a way to do this in a more aesthetic way...

The function do_something() is long-running, and must be interrupted after exactly one second.

like image 541
JohnRoach Avatar asked Oct 24 '22 18:10

JohnRoach


People also ask

How do I run a program at a specific time in Python?

Method 1: Using Time Module We can create a Python script that will be executed at every particular time. We will pass the given interval in the time. sleep() function and make while loop is true. The function will sleep for the given time interval.

How do I run a code at a specific time?

You can use perform(_:with:afterDelay:) to run a method after a certain number of seconds have passed, but if you want to run code at a specific time – say at exactly 4pm – then you should use Timer instead.

How do you call a method daily at a specific time in Python?

Schedule lets you run Python functions (or any other callable) periodically at pre-determined intervals using a simple, human-friendly syntax. Schedule Library is used to schedule a task at a particular time every day or a particular day of a week. We can also set time in 24 hours format that when a task should run.

Does Python have a time function?

Python has defined a module, “time” which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time is started measuring from 1 January, 12:00 am, 1970 and this very time is termed as “epoch” in Python.


1 Answers

I gather from comments that there's a while loop in here somewhere. Here's a class that subclasses Thread, based on the source code for _Timer in the threading module. I know you said you decided against threading, but this is just a timer control thread; do_something executes in the main thread. So this should be clean. (Someone correct me if I'm wrong!):

from threading import Thread, Event

class BoolTimer(Thread):
    """A boolean value that toggles after a specified number of seconds:

    bt = BoolTimer(30.0, False)
    bt.start()
    bt.cancel() # prevent the booltimer from toggling if it is still waiting
    """

    def __init__(self, interval, initial_state=True):
        Thread.__init__(self)
        self.interval = interval
        self.state = initial_state
        self.finished = Event()

    def __nonzero__(self):
        return bool(self.state)

    def cancel(self):
        """Stop BoolTimer if it hasn't toggled yet"""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.state = not self.state
        self.finished.set()

You could use it like this.

import time

def do_something():
    running = BoolTimer(1.0)
    running.start()
    while running:
        print "running"              # Do something more useful here.
        time.sleep(0.05)             # Do it more or less often.
        if not running:              # If you want to interrupt the loop, 
            print "broke!"           # add breakpoints.
            break                    # You could even put this in a
        time.sleep(0.05)             # try, finally block.

do_something()
like image 73
senderle Avatar answered Oct 27 '22 09:10

senderle