Task scheduler in java

 Description: This code executes for 10 seconds with 1 second delay ie. it keeps on executing for 10 seconds with time gap of 1 seconds.


TaskScheduler.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package download;

import static java.util.concurrent.TimeUnit.SECONDS;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class TaskScheduler {
  public static void main(String[] args) {

      // creating object of runnable interface
      Runnable obj_runnable = new Runnable() {
      public void run() {
      // task to run goes here

        System.out.println("Hello !!");

      }

    };


  //creating object of ScheduledExecutorService
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

 // calling obj_runnable here,  starting now (since we have defined 0), with a 1 second delay;   
    final ScheduledFuture<?> timeHandle =service.scheduleAtFixedRate(obj_runnable, 0, 1, TimeUnit.SECONDS);
   
 // Note:  ScheduledFuture is a delayed result-bearing action that can be cancelled
   
 //Schedule the event, and run for 10 sec. For 1 hour put 60 * 60 SECONDS
    service.schedule(new Runnable() {
      public void run() {
        timeHandle.cancel(false);
      }
    }, 10, SECONDS);
   

  }

}


Output: As time starts from zero 'Hello !!' is printed 11 times
Hello !!
Hello !!
Hello !!
Hello !!
Hello !!
Hello !!
Hello !!
Hello !!
Hello !!
Hello !!
Hello !!

No comments:

Post a Comment