How to execute Async task repeatedly after fixed time intervals

how to stop execution after a certain time in java
run thread for specific time java
android run task every minute
asynctask and handler in android
android-asynctask in loop
runnable vs asynctask
android run asynctask periodically
asynchronous programming in android

How to make Async task execute repeatedly after some time interval just like Timer...Actually I am developing an application that will download automatically all the latest unread greeting from the server and for that purpose I have to check for updates from server after some fixed time intervals....I know that can be easily done through timer but I want to use async task which I think is more efficient for android applications.

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
}

How to execute Async task repeatedly after fixed time intervals in , This example demonstrates how do I execute AsyncTask repeatedly after fixed time intervals in android.Step 1 − Create a new project in  This example demonstrates how do I execute AsyncTask repeatedly after fixed time intervals in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml.

  //Every 10000 ms   
       private void doSomethingRepeatedly() {
      Timer timer = new Timer();
      timer.scheduleAtFixedRate( new TimerTask() {
            public void run() {

                  try{

                     new SendToServer().execute(); 

                  }
                  catch (Exception e) {
                      // TODO: handle exception
                  }

             }
            }, 0, 10000);
                     }

How to execute Async task repeatedly after fixed time intervals, How to make Async task execute repeatedly after some time interval just like TimerActually I am developing an application that will download automatically all  To execute the task repeatedly after fixed interval of time we are going to use timer class. We are going to develop a sample application where the application prints hello Tutorials Point after every 5 seconds. So let’s get started, Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “HelloTutotrialsPoint”

You can just a handler:

private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handle m_handler;

@Override
protected void onCreate(Bundle bundle)
{
  ...
  m_handler = new Handler();
}

Runnable m_statusChecker = new Runnable()
{
     @Override 
     public void run() {
          updateStatus(); //this function can change value of m_interval.
          m_handler.postDelayed(m_statusChecker, m_interval);
     }
}

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

void stopRepeatingTask()
{
    m_handler.removeCallback(m_statusChecker);
}

But I would recommend you to check this framework: http://code.google.com/intl/de-DE/android/c2dm/ Is a different approach: the server will notify the phone when something is ready (thus, saving some bandwidth and performance:))

How to execute Async task repeatedly after fixed time intervals, async await in android async task timer android how to stop execution after a certain time in java runnable vs asynctask android asynctask alternative asynctask  How to execute Async task repeatedly after fixed t Create Thread for do work in every 2 minute in And ViewSwitcher Example in android; Download a file from URL to external Card in andro Set a image as Wallpaper from URL in android; Set Bitmap as Wallpaper in android May (35) April (7)

wouldn't it be more efficient to create a service and schedule it via Alarm Manager?

Repeating Periodic Tasks, repeatedly after some time interval just like TimerActually I am developing an application that will download automatically all the latest unread  How to execute Async task repeatedly after fixed t Create Thread for do work in every 2 minute in And ViewSwitcher Example in android; Download a file from URL to external Card in andro Set a image as Wallpaper from URL in android; Set Bitmap as Wallpaper in android May (35) April (7)

The accepted answer is problematic. Using TimerTask() for activating async task via handler is a bad idea. on orientation change you must remember to cancel also the timer and the handler calls. if not it will call the async task again and again on each rotation. It will cause the application to blow up the server (if this is rest http get request) instead of X time - eventually the calls will be instance many calls on each second. (because there will be many timers according to the number of screen rotations). It might crush the application if the activity and the task running in background thread are heavy. if you use the timer then make it a class memebr and cancel it onStop():

            TimerTask mDoAsynchronousTask;


            @Override
            public void onStop(){
               super.onStop();                 
               mDoAsynchronousTask.cancel();
               mHandler.removeCallbacks(null);
               ... 
            }


          public void callAsynchronousTask(final boolean stopTimer) {
             Timer timer = new Timer();
             mDoAsynchronousTask = new TimerTask() {
                 @Override
                 public void run() {
                     mHandler.post(new Runnable() {
                 ...

Instead try to avoid async task, and if you must then use scheduler service to run the async task. or the application class such as in this nice idea: https://fattybeagle.com/2011/02/15/android-asynctasks-during-a-screen-rotation-part-ii/

Or use simple handler (without the timer, just use postDelayed) and also good practive is to call cancel the async task onStop(). this code works fine using postDelayed:

           public class MainActivity extends AppCompatActivity {

                  MyAsync myAsync = new MyAsync();

                  private final Handler mSendSSLMessageHandler = new Handler();
                  private final Runnable mSendSSLRunnable = new Runnable(){

                  ..


                 @Override
                 protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    ConnectivityManager connMgr = (ConnectivityManager)   
                    getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
                    if (networkInfo != null && networkInfo.isConnected()) {
                            mSendSSLMessageHandler.post(mSendSSLRunnable);
                    }else
                    ..

                  @Override
                  public void onStop(){
                   super.onStop();
                      if ( progressDialog!=null && progressDialog.isShowing() ){
                           progressDialog.dismiss();
                      }
                    mSendSSLMessageHandler.removeCallbacks(mSendSSLRunnable);
                    myAsync.cancel(false);
                   }


              private final Runnable mSendSSLRunnable = new Runnable(){
              @Override
                public void run(){
                   try {
                    myAsync = new MyAsync();
                    myAsync.execute();
                   } catch (Exception e) {
                      // TODO Auto-generated catch block
                   }
                   mSendSSLMessageHandler.postDelayed(mSendSSLRunnable, 5000);
               }
          };


          class MyAsync extends AsyncTask<Void, Void, String> {
                boolean running = true;

                @Override
                protected void onPreExecute() {
                super.onPreExecute();
                  progressDialog = ProgressDialog.show               
                  (MainActivity.this, "downloading", "please wait");
                }

              @Override
              protected String doInBackground(Void... voids) {
                 if (!running) {
                       return null;
                  }
                 String result = null;
                 try{
                 URL url = new URL("http://192...");
                 HttpURLConnection urlConnection = (HttpURLConnection)            
                 url.openConnection();
                 InputStream in = new BufferedInputStream (urlConnection.getInputStream());
                 result = inputStreamToString(in);
                }catch(Exception e){
                   e.printStackTrace();
                }

               return result;
           }


    @Override
    protected void onCancelled() {
        boolean running = false;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        progressDialog.dismiss();
        try {

              ..


        } catch (JSONException e) {
            textView.append("json is invalid");
            e.printStackTrace();
        }

    }


}

Using the Timer and TimerTask Classes, How to make Async task execute repeatedly after some time interval just like Timer…Actually I am developing an application that will download  If you execute code like setTimeout(fn, 0) but then immediately after run a loop that counts from 1 to 10 billion, your callback will be executed after a few seconds. In the following example, the browser will wait two seconds before executing the anonymous function, then will display the alert message ( see it running live , and see the source code ):

Timer (Java Platform SE 8 ), periodic tasks: Handler - Execute a Runnable task on the UIThread after an optional delay Using a Handler , we can execute arbitrary code a single time after a specified delay: Execute Recurring Code with Specified Interval. Using a  Execute tasks in parallel using async and await to speed up computation. Suppose you have five tasks you want your computer to execute and that each takes 1 second to execute. In the old days, one would figure that each task would be executed sequentially, resulting in a total execution time of 5 seconds.

Cooperative asynchronous JavaScript: Timeouts and intervals , is an example of using a timer to perform a task after a delay: seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("​Time's up! HOUR_OF_DAY, 23); calendar.set(Calendar. When scheduling a task for repeated execution, you should use one of the schedule methods when  When a user clicks on the button, some void method should run after 30 seconds. There would be a void method DoAfterDelay that takes two input parameter. The first one is the method to do (using delegates), and the other one is the time interval.

Tasks may be scheduled for one-time execution, or for repeated execution at regular task for repeated fixed-delay execution, beginning after the specified delay. place at approximately regular intervals separated by the specified period. new GetMsgs().execute(); When I run this at the start of the event in android and even at a button click, it works and performs perfectly. But then when I tried to run this at a given interval to refresh the message screen, the application crashes.

Comments
  • A Async Task anyway runs in its own thread. Why run it on a handler ?
  • Yes, the async task does run on a separate thread, but cannot be started from other threads than the UI thread. The handler, I guess, is there for allowing that.
  • This technique leaves dangling references should the Activity that starts these AsyncTasks is killed (by an orientation change or an OS interruption like a phone call). So if you're happy with your programming crashing at these times, then use this method by all means.
  • @ScottBiggs What technique would be better/not crash?
  • @colti: Haven't found a good solution. I've abandoned ASyncTasks except for very simple stuff. For more complex actions I use Services (yeah, I know, the overhead is a pain-in-the-a$$, but at least it doesn't crash as much. Just be careful to clean up and not leave dangling Services).
  • It is recommend to favour ScheduledThreadPoolExecutor over Timer for all new code in the android documentation developer.android.com/reference/java/util/Timer.html
  • thanks alot.Actually I am just developing the client side of the application.Server side is already working for the same application developed for iphone and I have to use the same server for android
  • I'm new to threading in android. Where are you passing the runnable to the handler?
  • to answer @DheeB, the answerer does not mention it here, though it should be during instantiation like this m_handler = new Handler(m_statusChecker); Another reason this solution might not work, because the question is clearly indicating that there will be network operations "download automatically all the latest unread greeting from the server".. however, although you are using a handler, this handler/runnable is still running in the UI thread which is still blocking. You need to start it in a seperate thread manually.
  • Create a service is a pain, soo many things to take care on a service. I rather just use a Timer.
  • Services are easy to start and stop. Plus, they are not tied to the UI thread. So yes, I'd use a Service.
  • @IgorGanapolsky yes they are. But they also are a hassle, why would they create asyntask, timer, and these modules for smaller operations if they were non sense and everything would be done via a service ?
  • @tony9099 AsyncTask is intended for updating the UI thread upon completion. Service is not. As far as Timer - it's neither here nor there - it is not relevant for comparison between AsyncTask and Service...
  • I agree with Igor. Because of the problem of how Activities are killed when a device is rotated (and other times), AsyncTasks are guaranteed crashes unless very very carefully treated (which they are not in these examples). The real solution is to bite the bullet (yeah I know, it IS a pain) and do Services.