Tuesday, February 21, 2017

Task scheduling In Java

This is out of threading concept, threading is not used here. When you will run this example after a delay of 5 seconds a message will be printed in every 1 second:

Create a java file TaskScheduling.java in dev21century.threading package:
package dev21century.threading;

import java.awt.Frame;
import java.util.Timer;
import java.util.TimerTask;
class Task extends TimerTask
{
     int count = 1;
     /*run() is an abstract method
      which defines the task to be executed in scheduled
      interval */
     public void run() {
           System.out.println("Message from timer..");
     }
}

public class TaskScheduling {
     public static void main(String[] args) {

           Timer timer = new Timer();
           int delay = 5000; // 5 seconds
           int period = 1000; //repeate every seconds
           timer.scheduleAtFixedRate(new Task(), delay, period);
          
     }
}

Output:


No comments:

Post a Comment