How to Run an Async Task for Every X Mins in Android

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.

How to execute asynctask every 1 minute?

Use a Timer with a TimerTask. Define the following method in your Activity:

private void setRepeatingAsyncTask() {

final Handler handler = new Handler();
Timer timer = new Timer();

TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
AsyncTaskParseJson jsonTask = new AsyncTaskParseJson();
jsonTask.execute();
} catch (Exception e) {
// error, do something
}
}
});
}
};

timer.schedule(task, 0, 60*1000); // interval of one minute

}

Now call setRepeatingAsyncTask() from your onCreate() or onResume().

Android How to run an AsyncTask every second?

I think you are doing too many task in just one second. You could, instead, prepare all heavy staff in the onPreExecute() of the AsyncTask, read the XML and do the painting in the doInBackground(), resfresh the ImageView in the onProgressUpdate() and finally, when the task is done, save the image to the sdcard.

I've modified your Asynctask to accomplish the above scenario, I've not tested it but it gives you the idea.

In the onCreate() method of your activity you start the AsyncTask just once. It stays executing or sleeping until you set the Quit_Task variable to true. When the button is pressed you toggle the variable Do_Drawing: Do_Drawing=!Do_Drawing; and that's it.

private boolean Do_Drawing = false;
private boolean Quit_Task = false;

// READ XML FILE
class PositionAsync extends AsyncTask<Void, Void, Void>
{
Paint paintBlack;
BitmapFactory.Options myOptions;
Bitmap mutableBitmap2;
Canvas canvas2;
XMLHelper helper;

void Sleep(int ms)
{
try
{
Thread.sleep(ms);
}
catch (Exception e)
{
}
}

@Override
protected void onPreExecute()
{
// Prepare everything for doInBackground thread
paintBlack = new Paint();
paintBlack.setAntiAlias(true);
paintBlack.setColor(Color.BLACK);
myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
File ImageSource = new File("/sdcard/app_background3.jpg");
Bitmap bitmap2 = BitmapFactory.decodeFile(ImageSource.getAbsolutePath(), myOptions);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap2);
mutableBitmap2 = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
canvas2 = new Canvas(mutableBitmap2);
helper = new XMLHelper();
}

@Override
protected Void doInBackground(Void... arg0)
{
while (!Quit_Task)
{
// Sleep until button is pressed or quit
while (!Do_Drawing)
{
Sleep(1000);
if (Quit_Task)
return null;
}

float RoomWidthPx = canvas2.getWidth();
float RoomHeightPx = canvas2.getHeight();
float RoomXmeter = (float) 9.3;
float RoomZmeter = (float) 14.7;
// keep drawing until button is pressed again or quit
while (Do_Drawing)
{
if (Quit_Task)
return null;
helper.get();
for (PositionValue position : helper.positions)
{
String PosX = position.getPositionX();
String PosY = position.getPositionY();
String PosZ = position.getPositionZ();

float x = Float.valueOf(PosX);
float y = Float.valueOf(PosY);
float z = Float.valueOf(PosZ);

float xm = x * RoomWidthPx / RoomXmeter;
float zm = z * RoomHeightPx / RoomZmeter;

canvas2.drawCircle(xm, zm, 25, paintBlack);
}
this.publishProgress((Void) null);
Sleep(1000);
}
}
return null;
}

@Override
protected void onProgressUpdate(Void... progress)
{
// once all points are read & drawn refresh the imageview
try
{
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap2);
}
catch (Exception e)
{
e.printStackTrace();
}
}

@Override
protected void onPostExecute(Void result)
{
// SAVE DRAWINGS INTO FILE once the task is done.
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "app_background3.jpg");
mutableBitmap2.compress(Bitmap.CompressFormat.JPEG, 95, fos);
}
catch (Throwable ex)
{
ex.printStackTrace();
}
}
} // END READ XML FILE

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;
}
}

Execute AsyncTask several times

AsyncTask instances can only be used one time.

Instead, just call your task like new MyAsyncTask().execute("");

From the AsyncTask API docs:

Threading rules

There are a few threading rules that must be followed for this class to work properly:

  • The task instance must be created on the UI thread.
  • execute(Params...) must be invoked on the UI thread.
  • Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
  • The task can be executed only once (an exception will be thrown if a second execution is attempted.)

How to call asyncTasks periodically

Just use a timer.

final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
new UploadAsyncTask().execute();
new DownloadAsyncTask().execute();
}
});
}
};
timer.schedule(task, 0, 1000); //it executes this every 1000ms


Related Topics



Leave a reply



Submit