0

I have the following void:

public void onClick(View v) 
{
    PostDataTask postDataTask = new PostDataTask();

    postDataTask.execute(URL,textView3.getText().toString(),textView5.getText().toString(),textView12.getText().toString(),textView13.getText().toString(),textView14.getText().toString(),textView7.getText().toString(),textView15.getText().toString());

}

And I want to loop the "postDataTask.execute(...)" so it will be executed every 30 minutes for 24 hours (so executing 48 times in total). Can someone help me with this?

*EDIT

So I used the 1st suggestion given, but it only runs 1 time 60 seconds. Is it because it have the class in onCreate? :

@Override
protected void onCreate(Bundle savedInstanceState) {
    final PostDataTask postDataTask = new PostDataTask();
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    final Runnable exec = new Runnable() {
        public void run() {
            postDataTask.execute(URL, textView3.getText().toString(), textView5.getText().toString(), textView12.getText().toString(), textView13.getText().toString(), textView14.getText().toString(), textView7.getText().toString(), textView15.getText().toString());

        }
    };

    final ScheduledFuture execHandle = scheduler.scheduleAtFixedRate(exec, 60, 60, SECONDS);
    scheduler.schedule(new Runnable() {
        public void run() {
            execHandle.cancel(true);
        }
    }, 60 * 60, SECONDS);
  • 1
    Possible duplicate of [How to set a timer in android](http://stackoverflow.com/questions/1877417/how-to-set-a-timer-in-android) – Knells Nov 26 '15 at 20:57

1 Answers1

0

ScheduledExecutorService can do the thing.

Usage Example

Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
   private final ScheduledExecutorService scheduler =
     Executors.newScheduledThreadPool(1);

   public void beepForAnHour() {
     final Runnable beeper = new Runnable() {
       public void run() { System.out.println("beep"); 
     };
     final ScheduledFuture beeperHandle =
       scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
     scheduler.schedule(new Runnable() {
       public void run() { beeperHandle.cancel(true); }
     }, 60 * 60, SECONDS);
   }
 }}

Code from ScheduledExecutorService documentation

Damian Kozlak
  • 7,065
  • 10
  • 45
  • 51
  • I think this will work. Can I use it like I did below *EDIT ? –  Nov 26 '15 at 21:14
  • Yeah, that should do the thing. Although you can change from `MINUTES` to `SECONDS` to test it. – Damian Kozlak Nov 26 '15 at 21:25
  • It works well, but afterwards I came to the conclusion it wasn't really suited for the project. Nonetheless thanks for your response! –  Nov 26 '15 at 22:34
  • I checked code with fragment in `OnCreate` method and `Log.e` to check execution, it works. – Damian Kozlak Nov 26 '15 at 22:35