How to Run a Method Every X Seconds

How to run a method every X seconds

The solution you will use really depends on how long you need to wait between each execution of your function.

If you are waiting for longer than 10 minutes, I would suggest using AlarmManager.

// Some time when you want to run
Date when = new Date(System.currentTimeMillis());

try {
Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched

// Note: this could be getActivity if you want to launch an activity
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0, // id (optional)
someIntent, // intent to launch
PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
);

AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE
);

alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent
);
} catch(Exception e) {
e.printStackTrace();
}

Once you have broadcasted the above Intent, you can receive your Intent by implementing a BroadcastReceiver. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter); method. For more information on BroadcastReceiver's please refer to the official documentation..

public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("MyReceiver: here!") // Do your work here
}
}

If you are waiting for shorter than 10 minutes then I would suggest using a Handler.

final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second

handler.postDelayed(new Runnable() {
public void run() {
System.out.println("myHandler: here!"); // Do your work here
handler.postDelayed(this, delay);
}
}, delay);

What's the easiest way to call a function every 5 seconds in jQuery?

You don't need jquery for this, in plain javascript, the following will work!

var intervalId = window.setInterval(function(){
/// call your function here
}, 5000);

To stop the loop you can use

clearInterval(intervalId) 

What is the best way 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, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.

How to call a method every x seconds for x time in Xamarin Forms?

You could set a limit seconds for the Timer.

For example you want do something every 5 seconds for 2 minutes.

int sec = 120000; // 2 minutes
int period = 5000; //every 5 seconds

TimerCallback timerDelegate = new TimerCallback(Tick);
Timer _dispatcherTimer = new System.Threading.Timer(timerDelegate, null, period, period);// if you want the method to execute immediately,you could set the third parameter to null

private void Tick(object state)
{

Device.BeginInvokeOnMainThread(() =>
{
sec -= period;

if (sec >= 0)
{
//do something
}
else
{
_dispatcherTimer.Dispose();

}
});
}

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
isonline();
}

You can call InitTimer() in Form1_Load().

Call a function every X seconds

const reloadInterval = 60;

timer(0, reloadInterval).pipe(
mergeMap(_ => this.myService.myHttpCall())
).subscribe()

That's to answer your question. But honnestly I do not think that's a good idea to do that from a component and you should rather do that directly from your service.

Also, if you're looking for a more advanced answer you can take a look here.

How can I call a method every x seconds?

I think this should work for your needs.

created() {
this.interval = setInterval(() => this.getBitcoins(), 1000);
},

It's not necessary to register this on the created event, you can register it on other method, or even on a watcher.
If you do it that way, you'll have to check somehow that it hasn't been registered, cause it may cause multiple loops to run simultaneously.

How to call a function every x seconds but be able to do stuff in the meantime

This problem is solvable in multiple ways (another idea that comes to mind is multithreading, but that seems overkill). One approach would be to keep track of the number of "game cycles" and execute some function every n-th cycle like this:

for(int32_t count{1};;count++)
{
if (!count % 5)
{
// do something every 5th cycle
}
// do something every cycle
sleep(x);
}


Related Topics



Leave a reply



Submit