Python forking inside multithreading

I want to have a single server and a function to check for all computers in a network. I want to call the check for computers function on a regular basis with a fixed time period. So I would like to use 'select' to include the server and the function. Is it allowed to pass a function into select as a parameter or am I only allowed to pass lists into select?

What do you suggest I do to have a function called every 5sec or so?

Upvotes: 4

Views: 72

Answers (2)

Malik Brahimi
Malik Brahimi

Reputation: 16711

Try implementing your own thread that calls a passed function every five seconds.

from threading import *
import time

def my_function():
    print 'Running ...' # replace

class EventSchedule(Thread):
    def __init__(self, function):
        self.running = False
        self.function = function
        super(EventSchedule, self).__init__()

    def start(self):
        self.running = True
        super(EventSchedule, self).start()

    def run(self):
        while self.running:
            self.function() # call function
            time.sleep(5) # wait 5 secs

    def stop(self):
        self.running = False

thread = EventSchedule(my_function) # pass function
thread.start() # start thread

Upvotes: 4

laike9m
laike9m

Reputation: 19318

Simply use threading.Timer

import threading

def check_func():
    # other stuff
    threading.Timer(5.0, check_func).start()  # run check_func after 5s

check_func()

This is the standard way to do periodic job in python.

Upvotes: -1

Related Questions