Java Task Scheduler with and

Scheduling the task in java is now days getting day by day famous and we have lots of ways to schedule the task in java, below are some of the famous ways to schedule the task:

  1. Quartz
  2. and
  3. and

Here we are explaining scheduling task by using and, We can schedule task with below steps:

  1. is class which used to extend by Class in which run() method needs to be implement, exactly this menthod will be run in case scheduer run.
  2. Main Class is to be use, as we are using TimerExample here which will use Timer class, which will use schedule method which has 2 parameters. first parameter is the object of created of step 1 and second parameter is the long variable which will be a x seconds = x*1000

Now please find below the example code for the implementation.

Example Code

import java.util.Timer;
* @author
 public class TimerExample
    public static void main(String[] args) {
   Timer timer = new Timer();             // Get timer 1
    long delay = 5*1000;                   // 5 seconds delay
    timer.schedule(new Task(“Testing”),delay); }

import java.util.TimerTask;import java.text.SimpleDateFormat;import java.util.Date;
* This is a timertask because it extends the class java.util.TimerTask. This class
* will be given to the timer (java.util.Timer) as the code to be executed.
* @see java.util.Timer
* @see java.util.TimerTask
* @author
public class Task extends TimerTask {
private String _objectName;                 // A string to output
* Constructs the object, sets the string to be output in function run()
* @param str
Task(String objectName) {
this._objectName = objectName;
* When the timer executes, this code is run.
public void run() {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat(“dd.MM.yyyy hh:mm:ss”);
String current_time = format.format(date);
System.out.println(_objectName + ” – Current time: ” + current_time);}

One Comment