How to schedule a periodic task in Java?

JavaScheduled Tasks

Java Problem Overview


I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?

I'm currently using java.util.Timer.scheduleAtFixedRate. Does java.util.Timer.scheduleAtFixedRate support long time intervals?

Java Solutions


Solution 1 - Java

Use a ScheduledExecutorService:

 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);

Solution 2 - Java

You should take a look to Quartz it's a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time

Solution 3 - Java

Try this way ->

Firstly create a class TimeTask that run your task, it looks like:

public class CustomTask extends TimerTask  {

   public CustomTask(){
 
     //Constructor

   }

   public void run() {
       try {
	 
         // Your task process

       } catch (Exception ex) {
           System.out.println("error running thread " + ex.getMessage());
       }
	}
}

then in main class you instantiate the task and run it periodically started by a specified date:

 public void runTask() {

        Calendar calendar = Calendar.getInstance();
        calendar.set(
           Calendar.DAY_OF_WEEK,
           Calendar.MONDAY
        );
        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 40);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);


	
        Timer time = new Timer(); // Instantiate Timer Object

        // Start running the task on Monday at 15:40:00, period is set to 8 hours
        // if you want to run the task immediately, set the 2nd parameter to 0
        time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}

Solution 4 - Java

Use Google Guava AbstractScheduledService as given below:

public class ScheduledExecutor extends AbstractScheduledService {

   @Override
   protected void runOneIteration() throws Exception {
      System.out.println("Executing....");
   }

   @Override
   protected Scheduler scheduler() {
        return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
   }

   @Override
   protected void startUp() {
       System.out.println("StartUp Activity....");
   }


   @Override
   protected void shutDown() {
       System.out.println("Shutdown Activity...");
   }

   public static void main(String[] args) throws InterruptedException {
       ScheduledExecutor se = new ScheduledExecutor();
       se.startAsync();
       Thread.sleep(15000);
       se.stopAsync();
   }
}

If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.

Solution 5 - Java

If you want to stick with java.util.Timer, you can use it to schedule at large time intervals. You simply pass in the period you are shooting for. Check the documentation here.

Solution 6 - Java

Do something every one second

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        //code
    }
}, 0, 1000);

Solution 7 - Java

These two classes can work together to schedule a periodic task:

Scheduled Task

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

Run Scheduled Task

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

Solution 8 - Java

If your application is already using Spring framework, you have Scheduling built in

Solution 9 - Java

I use Spring Framework's feature. (spring-context jar or maven dependency).

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
public class ScheduledTaskRunner {

    @Autowired
    @Qualifier("TempFilesCleanerExecution")
    private ScheduledTask tempDataCleanerExecution;

    @Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
    public void performCleanTempData() {
        tempDataCleanerExecution.execute();
    }

}

ScheduledTask is my own interface with my custom method execute, which I call as my scheduled task.

Solution 10 - Java

Have you tried Spring Scheduler using annotations ?

@Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
    //body can be another method call which returns some value.
}

you can do this with xml as well.

 <task:scheduled-tasks>
   <task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
 <task:scheduled-tasks>

Solution 11 - Java

my servlet contains this as a code how to keep this in scheduler if a user presses accept

if(bt.equals("accept")) {
    ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
    String lat=request.getParameter("latlocation");
    String lng=request.getParameter("lnglocation");
    requestingclass.updatelocation(lat,lng);
}

Solution 12 - Java

There is a ScheduledFuture class in java.util.concurrent, it may helps you.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAriyanView Question on Stackoverflow
Solution 1 - Javab_erbView Answer on Stackoverflow
Solution 2 - JavaJorgeView Answer on Stackoverflow
Solution 3 - JavaShessukyView Answer on Stackoverflow
Solution 4 - JavaAride ChettaliView Answer on Stackoverflow
Solution 5 - JavaBelizzleView Answer on Stackoverflow
Solution 6 - JavaDuchicView Answer on Stackoverflow
Solution 7 - JavaSumiSujithView Answer on Stackoverflow
Solution 8 - JavaBlackView Answer on Stackoverflow
Solution 9 - JavaYan KhonskiView Answer on Stackoverflow
Solution 10 - Javamadhu_karnatiView Answer on Stackoverflow
Solution 11 - Javagopal krishna maretiView Answer on Stackoverflow
Solution 12 - JavanAkhmedovView Answer on Stackoverflow