473,320 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Stopping a Thread with Time Slicing

Hi All,

I've been trying to come up with a good way to run a certain process
at a timed interval (say every 5 mins) using the SLEEP command and a
semaphore flag. The basic thread loop was always sitting in the sleep
command and not able to be interrupted. When the time came to set the
semaphore flag to false (stopping the thread), my program would have
to wait up to the entire sleep time to break out of the loop.

I have finally found a very workable solution to break out of the
sleep loop by using a time slicing loop to divide the overall sleep
time into small pieces (slices) giving the loop more opportunities to
be interrupted.
Here is my code :

-------------------------------------------------------------

import time
import datetime
import threading
def log(message):

now = datetime.datetime.now().strftime("%H:%M:%S")
print "%s : %s" % (now, message)

class StoppableThread(threading.Thread):

def __init__(self, sleep_time, time_slice):

self.sleep_time = sleep_time
self.running = True
self.time_slice = time_slice

threading.Thread.__init__(self)
def run(self):

while self.running:

log('Thread Running...')
#process_some_data() ## <<-- Call some def here to perform
some timed task
log('## Do Some Work Here ##\n')

# Sleep Loop :
# Put sleeps in time_slice loop, with sleep = sleep_time /
time_slice
# This gives the sleep loop more opportunities to be interrupted
# when the running flag is set to False

for current_loop in range(0, self.time_slice) :

time.sleep(self.sleep_time / self.time_slice)

if not self.running: # check the flag
break # break out of the sleep loop
log('** Thread Has STOPPED!')
def stop(self): # stop the thread from running
self.running = False
################################################## ###################
# T E S T
################################################## ###################

SMALL_SLEEP = 35
CHECK_SLEEP = 300 # sleep interval in seconds to run a timed
process
TIME_SLICE = 100 # number of slices to divide CHECK_TIME
(higher number = faster kill response)
log('Create Thread')
thread_obj = StoppableThread(CHECK_SLEEP, TIME_SLICE)

log('Thread Start\n')
thread_obj.start()

for current_loop in range(0,10):
time.sleep(SMALL_SLEEP)
log('current loop = %d \n' % current_loop)

log('Thread Stop')
thread_obj.stop()

log('Done!')
--------------------------------------------

Test Results :
>python Simple_Thread.py
15:37:23 : Create Thread
15:37:23 : Thread Start

15:37:23 : Thread Running...
15:37:23 : ## Do Some Work Here ##

15:37:58 : current loop = 0

15:38:33 : current loop = 1

15:39:08 : current loop = 2

15:39:43 : current loop = 3

15:40:18 : current loop = 4

15:40:53 : current loop = 5

15:41:28 : current loop = 6

15:42:03 : current loop = 7

15:42:23 : Thread Running...
15:42:23 : ## Do Some Work Here ##

15:42:38 : current loop = 8

15:43:13 : current loop = 9

15:43:13 : Thread Stop
15:43:13 : Done!
15:43:14 : ** Thread Has STOPPED!
Oct 2 '08 #1
2 3322
Steve wrote:
Hi All,

I've been trying to come up with a good way to run a certain process
at a timed interval (say every 5 mins) using the SLEEP command and a
semaphore flag. The basic thread loop was always sitting in the sleep
command and not able to be interrupted. When the time came to set the
semaphore flag to false (stopping the thread), my program would have
to wait up to the entire sleep time to break out of the loop.

I have finally found a very workable solution to break out of the
sleep loop by using a time slicing loop to divide the overall sleep
time into small pieces (slices) giving the loop more opportunities to
be interrupted.
A better approach for this is to use a Python Event or Condition object:
http://docs.python.org/library/threading.html#id5

Example code:
import threading
my_stop_event = threading.Event()

# Sleep Loop :
#for current_loop in range(0, self.time_slice) :
# time.sleep(self.sleep_time / self.time_slice)

event.wait(self.sleep_time)
if not self.running: # check the flag
break # break out of the sleep loop

# From another thread, you can notify the above sleeping thread using:
my_stop_event.set()
Cheers,
Todd
Oct 2 '08 #2
Hi Todd,

Thanks for your suggestions on using the Event condition methods on
this thread.

Here is my updated code :
import time
import datetime
import threading
def log(message):

now = datetime.datetime.now().strftime("%H:%M:%S")
print "%s : %s" % (now, message)

class StoppableThread(threading.Thread):

def __init__(self, sleep_time, function, args=[], kwargs={}):

self.sleep_time = sleep_time

threading.Thread.__init__(self)

self.function = function
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()
def run(self):

while not self.finished.isSet(): # loop while condition
is true
log('** Doing Work')
self.function(*self.args, **self.kwargs) # run the function
self.finished.wait(self.sleep_time) # put thread in wait
state
log('** Thread Has STOPPED!')
def stop(self): # stop the thread from running
log('* Stopping Thread')
self.finished.set()
self.join()


def my_function (a, b, c):
log('my_function running... %s' % a)
################################################## ###################
# T E S T
################################################## ###################

SMALL_SLEEP = 35
CHECK_SLEEP = 300 # sleep interval in seconds to run a timed
process
log('Create Thread')
thread_obj = StoppableThread(CHECK_SLEEP, my_function, (15,0,-1))
log('Thread Start\n')
thread_obj.start()

for current_loop in range(0,10):
time.sleep(SMALL_SLEEP)
log('current loop = %d \n' % current_loop)

log('Call Thread Stop')
thread_obj.stop()

log('Done!')
Test Output :
>python Simple_Thread_Stop_Event.py
12:58:42 : Create Thread
12:58:42 : Thread Start

12:58:42 : ** Doing Work
12:58:42 : my_function running... 15
12:59:17 : current loop = 0
12:59:52 : current loop = 1
13:00:27 : current loop = 2
13:01:02 : current loop = 3
13:01:37 : current loop = 4
13:02:12 : current loop = 5
13:02:47 : current loop = 6
13:03:22 : current loop = 7
13:03:42 : ** Doing Work
13:03:42 : my_function running... 15
13:03:57 : current loop = 8

13:04:32 : current loop = 9

13:04:32 : Call Thread Stop
13:04:32 : * Stopping Thread
13:04:32 : ** Thread Has STOPPED!
13:04:32 : Done!
On Oct 2, 4:40*pm, Todd Whiteman <to...@activestate.comwrote:
Steve wrote:

A better approach for this is to use a Python Event or Condition object:http://docs.python.org/library/threading.html#id5

Example code:

import threading
my_stop_event = threading.Event()

* * * *# Sleep Loop :
* * * *#for current_loop in range(0, self.time_slice) :
* * * *# *time.sleep(self.sleep_time / self.time_slice)

* * * *event.wait(self.sleep_time)
* * * *if not self.running: * *# check the flag
* * * * *break * * * * * * * * # break out of the sleep loop

# From another thread, you can notify the above sleeping thread using:
my_stop_event.set()

Cheers,
Todd
Oct 3 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Keith | last post by:
I'm in the same boat as the fellow who posted this message back in August: Title : Windows Service, How does one make a service "fail" properly? Author : Ross Bennett Group :...
2
by: matteo | last post by:
Hi everyboby, i wrote a c# service that every XXX minute launch a working thread on timer events, something like this: private void timer_Elapsed ( object status ) { // Worker thread...
11
by: Steve | last post by:
I'm having a problem with my Thread usage and I think the general design of how I'm working with them. My UI class calls a method in another class that does a lot of work. That "worker" class...
1
by: mclaugb | last post by:
Here is a simple piece of thread code. When i add the print (or other) function into the run method--the thread fails to stop after 2 seconds which the join(2) should ensure. I have a function...
4
by: bjm | last post by:
I am writing a program that will automate a series of application installations. I want to give the user the option of stopping the program's execution in between installations (for example, give...
2
by: tshad | last post by:
I have a Service that starts a thread that never ends. When I stop the service from the Service Applet, does it kill the thread or do I need to do it myself? If it isn't killed, what happens...
10
by: archana | last post by:
Hi all, I am having one windows service which is updating to database. On 'Onstop i want to wait till current updation complete. How will i do this? Because if i write some lengthy code on...
4
by: =?iso-8859-1?B?S2VyZW0gR/xtcvxrY/w=?= | last post by:
Hi, i have a main thread an another worker thread. The main Thread creates another thread and waits for the threads signal to continue the main thread. Everything works inside a ModalDialog and...
1
by: raghudr | last post by:
Hi all, I am displaying a splash screen for which i have created a thread.Since my whole project is launched by windows service and that service will start automatically at the start of the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.