How to Execute Async Task Repeatedly After Fixed Time Intervals

How to execute Async task repeatedly after fixed time intervals


public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms
}

Run async method regularly with specified interval

The async equivalent is a while loop with Task.Delay (which internally uses a System.Threading.Timer):

public async Task PeriodicFooAsync(TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
await FooAsync();
await Task.Delay(interval, cancellationToken)
}
}

It's important to pass a CancellationToken so you can stop that operation when you want (e.g. when you shut down your application).

Now, while this is relevant for .Net in general, in ASP.Net it's dangerous to do any kind of fire and forget. There are several solution for this (like HangFire), some are documented in Fire and Forget on ASP.NET by Stephen Cleary others in How to run Background Tasks in ASP.NET by Scott Hanselman

Repeating AsyncTask.execute()

Create AsyncTask class object each time when you want to excute.

Example

    Task _task=new Task();
_task.excute();

For More Info Read This Tutorial Link

Running an Async Task Inside a timer in Android

Important remove code
new GetMsgs().execute();

from the Timer and start it in the onCreate method of your activity and on Destroy method of your activity stop your async task

 class GetMsgs extends AsyncTask<String, String, String> {

boolean flag = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
flag = true;
}

@Override
protected String doInBackground(String... arg0) {
while(flag)
{
publishProgress("start");

//Your Code what you are doing in the Do inBackground

try
{
Thread.sleep(3000);//Your Interval after which you want to refresh the screen
}
catch (InterruptedException e)
{
}
publishProgress("stop");

}
return null;
}
@Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
if(values[0].equalsIgnoreCase("start"))
{
//Create Your Dialog in it
//Do here what you are doing in the onPreExecute
}
else if(values[0].equalsIgnoreCase("stop"))
{
//Code you are doing in the onPostExecute
}

}
@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
flag = false;
}
}

How to run an async task for every x mins in android?

You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event. Here is a short snippet:

private final static int INTERVAL = 1000 * 60 * 2; //2 minutes
Handler mHandler = new Handler();

Runnable mHandlerTask = new Runnable()
{
@Override
public void run() {
doSomething();
mHandler.postDelayed(mHandlerTask, INTERVAL);
}
};

void startRepeatingTask()
{
mHandlerTask.run();
}

void stopRepeatingTask()
{
mHandler.removeCallbacks(mHandlerTask);
}

Note that doSomething should not take long (something like update position of audio playback in UI). If it can potentially take some time (like downloading or uploading to the web), then you should use ScheduledExecutorService's scheduleWithFixedDelay function instead.

Dismiss async task after sometime

http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)

Execute method in a loop after a minimum time interval using Task.WhenAll or similar

You do not await the toplevel task (Since you do not have one). Try this:

class Program
{
static void Main(string[] args)
{
while (true)
{
Run().Wait(); // Wait on each iteration.
}
}

// Need to return Task to be able to await it.
static async Task Run()
{
var task1 = Task.Delay(500);
var task2 = DoSomethingAsync();

await Task.WhenAll(task1, task2);
}

static async Task DoSomethingAsync()
{
Random r = new Random();
int miliseconds = Convert.ToInt32(r.NextDouble() * 1000);
await Task.Delay(miliseconds);
Console.WriteLine(miliseconds);
}
}

Now, there is a catch in using .Wait(): it blocks execution. See this excellent guide: https://msdn.microsoft.com/en-us/magazine/jj991977.aspx for more details. But don't worry, for the Main method of a Console App it is perfectly safe.

The same guide explains also why you should always try to return a Task instead of using async void MyTask() { ... }. In your case it prevents you from waiting for the Run() method to complete.

Running doInBackground repeatedly in android asynchTask

Check this question: How to execute Async task repeatedly after fixed time intervals

It has already been asked several times.

A infinite loop is not a good way to go!

If you want to fetch data even if your Activity is in background/or not running, a Service would be the better way.

public class MyService extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);

MyAsyncTask MyTask = new MyAsyncTask ();
MyTask.execute();

return Service.START_STICKY; // if android our the user kills the Service it will restart
}
}

private class MyAsyncTask extends AsyncTask<String, Void, String> {


@Override
protected String doInBackground(String... params) {
// do your long/network operation
}

@Override
protected void onPostExecute(String result) {

// send Intent to BroadcastReceiver in MainActivity.class to know the service finished its task once
Intent finished = new Intent("yourPackage.DOWNLOADCOMPLETE");
sendBroadcast(finished);
}

@Override
protected void onPreExecute() {
}

@Override
protected void onProgressUpdate(Void... values) {
}
}
}

In your MainActivity add a BroadcastReceiver:

@Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}

public void onResume() {
super.onResume();

IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
}

// notify when operation in Service finished
private ResponseReceiver receiver;

public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "yourPackage.DOWNLOADCOMPLETE";

@Override
public void onReceive(Context context, Intent intent) {

// do stuff if Service finished its task at least once
}
}

Start the Servive every 60 seconds using AlarmManager:

// refresh every 60 seconds in MyService.java
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 60 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*1000, pintent);

startService(intent);

In your AndroidManifest.xml you have to register the Service:

<service
android:enabled="true"
android:name=".MyService"
android:label="your Service Name">
</service>

android:label="your Service Name" will be displayed if you navigate to running apps in android.

Asynchronous Repeating Scheduled Task

As other suggested in the comments. So let me elaborate it more.

DON'T USE AsyncTask. INSTEAD GO FOR IntentService ONLY.

  1. Make a class extends IntentService
  2. Use Alarm Manager to trigger a intent to your own service with specific action item
  3. Define a Interface to be used to notify client of this service.
  4. Maintain a list of these interface implemenation object provided by its client.
  5. in onHandleIntent(Intent intent) identify the call by checking action.
  6. Initiate the data fetch request directly on intentService as the use worker thread to work and in the end call update delegate of the interface object list you maintained.

  7. Make methods to Let Activity register and unregister from listening these updates.

  8. Which is actually adding the interface implementation provided by them in the list you maintained and remove from it when unregister gets called.
  9. make sure activity register itself in onResume and unregister itself in the onPause.
  10. Either use Repeating alarm or initiate one again in the end of single operation run.
    I hope it helps :)


Related Topics



Leave a reply



Submit