Run a java function after a specific number of seconds

new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { // your code here } }, 5000 ); EDIT: javadoc says: After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer’s task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can … Read more

How to repeatedly execute a function every x seconds?

If your program doesn’t have a event loop already, use the sched module, which implements a general purpose event scheduler. import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print(“Doing stuff…”) # do your stuff sc.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_something, (s,)) s.run() If you’re already using an event loop library like asyncio, trio, … Read more

How do you use a TimerTask to run a thread?

I have implemented something like this and it works fine: private Timer mTimer1; private TimerTask mTt1; private Handler mTimerHandler = new Handler(); private void stopTimer(){ if(mTimer1 != null){ mTimer1.cancel(); mTimer1.purge(); } } private void startTimer(){ mTimer1 = new Timer(); mTt1 = new TimerTask() { public void run() { mTimerHandler.post(new Runnable() { public void run(){ //TODO … Read more

Resettable Java Timer

According to the Timer documentation, in Java 1.5 onwards, you should prefer the ScheduledThreadPoolExecutor instead. (You may like to create this executor using Executors.newSingleThreadScheduledExecutor() for ease of use; it creates something much like a Timer.) The cool thing is, when you schedule a task (by calling schedule()), it returns a ScheduledFuture object. You can use … Read more

Best timing method in C?

I think this should work: #include <time.h> clock_t start = clock(), diff; ProcessIntenseFunction(); diff = clock() – start; int msec = diff * 1000 / CLOCKS_PER_SEC; printf(“Time taken %d seconds %d milliseconds”, msec/1000, msec%1000);

.NET, event every minute (on the minute). Is a timer the best option?

Building on the answer from aquinas which can drift and which doesn’t tick exactly on the minute just within one second of the minute: static System.Timers.Timer t; static void Main(string[] args) { t = new System.Timers.Timer(); t.AutoReset = false; t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed); t.Interval = GetInterval(); t.Start(); Console.ReadLine(); } static double GetInterval() { DateTime now … Read more