Forums

Some codes are ignored before os.kill() in sheduled task log

Here's code.

import os
import signal
import time

pid = os.getpid()

timeStart = time.time()
timeEnd = time.time() + 5

while True:
    timeSpend = 5 - int(time.time() - timeStart)
    print "%02d Seconds Left" % timeSpend    
    time.sleep(1)

    if timeEnd <= time.time():
        print "DONE!!!!!!"
        time.sleep(1)
        os.kill(pid, signal.SIGTERM)

It works good in my console bash.

enter image description here

But when i try this code in scheduled task, It's not good.

enter image description here

There is just 'terminated' message in log.

How can i print message right?

Try adding

import sys

...at the start, and then

sys.stdout.flush()

...after each "print" statement. When you're writing to the screen, Python just prints the message right away. But when you're writing to a file (which you essentially are doing when you're running a schedule task that logs to a file) then it buffers things and only writes when the buffer fills up. That's generally more efficient, but can cause problems if the process is killed unexpectedly. Flushing the buffer makes sure that your printed data is written to disk immediately.

Yeah, it works! I am learning many things from here. Thanks.