I am optimization a function choosing different parameters. However, for some parameters, it will loop forever. So I want to set a timer like following: (just an example)
function optim(theta)
if run time of function x(theta) > 1min
return inf
else return x(theta)
end
I’ve done something like this before in an extremely hacky way, which I’ll describe below. I would wager good money there’s something better with tasks and threads and I’d be excited to learn it.
Set up a channel, but don’t put anything in it. The function you’ll interrupt needs to take a channel as an argument.
Modify your function code so that it periodically checks if the channel has a value; if so, the function immediately returns.
Create two tasks: one to execute the function, and one to sleep for a minute before adding a value to the channel.
That way, after ~1 minute the channel will have a value, and the next time the long-running function checks the channel, it’ll immediately return.
this actually doesn’t sound too bad…and it also have the plus side that, you can first don’t push anything into the channel, and then manually interrupt it — I guess it combines check time_ns() and just have a new REPL running.