SoFunction
Updated on 2025-04-11

How to implement a timed task in java

Java implements a timed task

Requirement description

The project needs to update mysql data regularly to another database every day, and the update task is temporarily started at 12:00 noon every day.

There are three ways to implement it

The first type

Use the timeTask and Calendar that comes with javaJDK to implement timing tasks. This method can set delays, execution intervals, and execution time points. This is what I use.

//The first type: start the task regularly at 12 noon every daypublic static void main(String[] args) {
        //Calendar technology is also done based on java threads        //Set the time point for the first update        Calendar calendar = ();
        (Calendar.HOUR_OF_DAY, 12);//Control hours        (, 0);//Control minutes,        (, 0);//Control seconds,         //Use Java API Timer to complete a timed task        Timer timer = new Timer();
        TimerTask task=new TimerTask() {
            @Override
            public void run() {
            // Implement your own scheduled task operations                ("This is a timed task! Go update the database data!");

            }
        };
        /*
         * The task starts at 12:00 of the first posting task, and executes it regularly every (1000 * 60 * 60 * 24) days.
         * */
        (task, () , 1000 * 60 * 60 * 24);
    }
    
//The second type: timed update, start the timed task at startup, start the task every 2 seconds    public static void main(String[] args) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                ("Timed Task Start" + new Date());
            }
        };
        Timer timer = new Timer();
//Method parameters, timed execution content, delay (unit milliseconds), execution interval (unit milliseconds)        (timerTask,100,2000);
    }

The second type

Use ScheduledExecutorService to execute timing tasks, which is also built into JDK. The threads of the timing tasks it executes are taken from the thread pool, and the tasks are carried out in parallel and do not affect each other.

/**
  * Use ScheduledExecutorService to execute timing tasks
  */
public class get003 {
    public static void main(String[] args) {
        ScheduledExecutorService service = ();
        //Parameters; task body, delay time for first execution, interval for task execution, interval time unit        (()-> ("Task Start"+new Date()),0,3, );
    }
}

The third type

(Recommended) Use springboot annotation to implement timing tasks, create a new task class, add @Component and @EnableScheduling annotations to the class, add @Scheduled annotations to the method, add start time to the attribute cron of the @Scheduled annotation, and then start the project. When the task starts, the task method will be executed.

You can define multiple timing tasks in this class, just add the @Scheduled annotation to each task method.

/**
  * Timed task, add @Component and @EnableScheduling annotations to the main class, and add @Scheduled annotations to the method
  * Note that you can add a switch to determine whether the task is executed
  */
@Slf4j
@Component
@EnableScheduling
public class TaskInfo {
//Read the value of the switch from the configuration file    @Value("${-open}")
    private boolean flag;
    @Scheduled(cron = "${-corn}")
    public void m1() {
//Judge switch status        if (flag){
            SimpleDateFormat stf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = (new Date());
            ("Timed Task Start->>" + format);
        }else {
            ("The timing task switch is not turned on, please try again!");
        }
    }
}
  • @Value: Read attribute values ​​from configuration file
  • cron: Special time format, time, minute, second, year, month, day and day have different expression forms.

Here I set up a task switch. When the project is deployed on multiple servers, how do I want to have only one machine running the timing task at a certain point in time? I can set other switches to false, and the switch that needs to be started is set to true, so that the start of the timing task can be flexibly controlled. The configuration file timing task configuration is as follows:

  #Scheduled taskstask:
    switch:
      is-open: false #switch    corn:
      task-corn: 0 48 21 * * ? #Timed task time format

2021-08-16 21:47:31.255  INFO 8888 --- [           main]   : Starting service [Tomcat]
2021-08-16 21:47:31.255  INFO 8888 --- [           main]  : Starting Servlet engine: [Apache Tomcat/9.0.38]
2021-08-16 21:47:31.555  INFO 8888 --- [           main] .[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-08-16 21:47:31.555  INFO 8888 --- [           main] : Root WebApplicationContext: initialization completed in 1174 ms
2021-08-16 21:47:31.956  INFO 8888 --- [           main]  : Initializing ExecutorService 'applicationTaskExecutor'
2021-08-16 21:47:32.104  INFO 8888 --- [           main]          : Initializing ExecutorService 'taskScheduler'
2021-08-16 21:47:32.151  INFO 8888 --- [           main]  : Tomcat started on port(s): 8080 (http) with context path ''
2021-08-16 21:47:32.165  INFO 8888 --- [           main]               : Started PdosWebApplication in 2.181 seconds (JVM running for 3.035)
The purchase and sale web startup was successfully launched!
The timing task switch is not turned on, please try again!

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.