2

I have the following python script. I want to repeatedly execute timer function after every 10 seconds which I am running asynchronously. I looked at post1 and post2 but they are not returning any value.

import threading
def timer(bar, baz):
  print 'hello {0}'.format(bar)
  return 'foo' + baz

from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)

async_result = pool.apply_async(timer, ('world', 'foo'))

return_val = async_result.get()
print return_val

Is there a way to get the value after every t time intervals while main thread is still doing some other job?

Community
  • 1
  • 1
Paul Schimmer
  • 161
  • 3
  • 22

1 Answers1

0

One way to go about it using what you linked to:

from threading import Timer
from multiprocessing.pool import ThreadPool
from time import sleep

def getLast():
    global got
    Timer(10,getLast).start()
    got = async_result.get()

def action(bar, baz):
    print 'hello {0}'.format(bar)
    return 'foo ' + baz

pool = ThreadPool(processes=1)
async_result = pool.apply_async(action, ('world', 'foo'))
Timer(10,getLast).start()

string = 'a'
while True:
    got = None
    while got is None:
        sleep(2)
        print 'Doing stuff'
    print 'Got:',got
    async_result = pool.apply_async(action, ('world', 'foo '+string))
    string +='a'
    got = None

The inner while emulates main thread 'doing stuff', and every 10 seconds you should get a new result from async_result, and jump start a new non-blocking run. The outer loop just keeps the main thread running.

kabanus
  • 24,623
  • 6
  • 41
  • 74