0

I just want a function to finish in a specific time period (suppose within 5 secs) and return some value. In case it doesn't finish in 5 secs it should return a fail status (lets say 1). If below example executed within 5 secs it should return hostname, else return empty string or something else

def processFile(logfile):
    file = open(logfile, 'a+')
    hostname = "karma"
    file.write('%s,%d,\"%s\",%s,%s;\n' %('\"JOB_NEW\"',int(time.time()),hostname,no_of_cpu,user))
    return (hostname)

processFile(logfile)
Georgy
  • 12,464
  • 7
  • 65
  • 73
niraj pandey
  • 102
  • 7
  • Should the fail status be sent immediately after 5 secs or should it be sent when the code is finished, e.g. after 10 secs? – Tobias Brösamle Jan 25 '19 at 09:43
  • @Tobias It should sent the status immediately – niraj pandey Jan 25 '19 at 09:47
  • In this case, I think you have no other choice than spawning a working thread that performs the actual job, then you can check if the code returned after 5 sec, otherwise you kill the thread and return fail status. – Tobias Brösamle Jan 25 '19 at 09:53
  • In some cases, there might be another solution. Let's say, you're doing work in a loop. The loop takes lot of time because there are many iterations, but the work done per iteration is just minimal. In this case, you could check the time in every iteration and return the fail status if the time limit is exceeded, otherwise at the end you return the calculated value. But that's probably just a special case. – Tobias Brösamle Jan 25 '19 at 09:59
  • Possible duplicate of [Timeout on a function call](https://stackoverflow.com/questions/492519/timeout-on-a-function-call) – Georgy Jan 25 '19 at 10:37
  • @TobiasBrösamle: unfortunately, Python has no clean and neat way to terminate a thread. See https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread – Serge Ballesta Jan 25 '19 at 10:37
  • @SergeBallesta: I didn't know, as I never had to do such a thing. But now that I searched for it for a few seconds, it seems there's generally (also in other languages) a lack of such a feature. – Tobias Brösamle Jan 25 '19 at 11:21

0 Answers0