spring boot application - scheduled tasks

Posted by Daddy on Sun, 06 Mar 2022 11:06:02 +0100

I wrote the script of Oracle scheduled task before. At that time, the script was added to the task plan for the Windows server server, but I encountered that the script could not be added to the task plan in practice (I tried all kinds of methods but could not be added). This is what I thought. Can I write a scheduled task to call the script? Yes, indeed. Source address GitHub

Updated at 21:51 on June 2, 2019 (the time of scheduled task is dynamically adjusted. The previous scheduled task is written on the annotation, which is newly modified to call the fields in h2 table)

Add @ enableshcheduling annotation to spring boot main program

Define components using @ Component

Use @ Scheduled to define Scheduled tasks in the component

JavaRunBatApplication.java

package cn.geoary;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class JavaRunBatApplication {
    public static void main(String[] args) {
        SpringApplication.run(JavaRunBatApplication.class, args);
    }
}

JavaRunBat.java

package cn.geoary.util;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: java-run-bat
 * @description: Java Execute bat files regularly
 * @author: geoary
 * @create: 2019-05-06 14:41
 **/
@Component
public class JavaRunBat {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    /**
     * @description Create scheduled task
     * @param
     * @return
     * @author geoary
     * @date 2019/5/6 
     */
    // Execute at 1:00 every day
    @Scheduled(cron = "0 0 1 * * ?")
    // Once every 3 minutes
    //@Scheduled(cron = "0 0/3 * * * ?")
    public void timingBat(){
        runBat();
    }
    /**
     * @description Execute bat file 
     * @param  
     * @return  
     * @author geoary
     * @date 2019/5/6 
     */
    public static void runBat(){
        String batPath = "E:/backup/data/autobackup.bat";
        execBat(batPath);
        //execBat("1", batPath);
    }
    /**
     * @description Execute bat 
     * @param
     * @return  
     * @author geoary
     * @date 2019/5/6 
     */
    public static void execBat(String ways, String batPath){
        String cmdPre;
        switch (ways){
            case "1":
                // Yes, close the command window after executing the dir command
                cmdPre =  "cmd /c ";
                break;
            case "2":
                // Is not to close the command window after executing the dir command
                cmdPre = "cmd /k ";
                break;
            case "3":
                // A new window will be opened and the dir instruction will be executed, and the original window will be closed
                cmdPre = "cmd /c start ";
                break;
            default:
                // A new window will be opened and the dir instruction will be executed. The original window will not be closed
                cmdPre = "cmd /k start ";
        }
        String cmd = cmdPre + batPath;
        try{
            Process ps = Runtime.getRuntime().exec(cmd);
            InputStream in = ps.getInputStream();
            int c;
            while ((c = in.read()) !=  -1){

            }
            in.close();
            try {
                ps.waitFor();
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("Execution complete"+dateFormat.format(new Date()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void execBat(String batPath){
        try{
            Process ps = Runtime.getRuntime().exec("cmd /c start "+ batPath);
            InputStream in = ps.getInputStream();
            int c;
            while ((c = in.read()) !=  -1){
            }
            in.close();
            try {
                ps.waitFor();
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("Execution complete"+dateFormat.format(new Date()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

Scheduled task cron expression:

The general expression is as follows:

Execute @ scheduled at 1 a.m. every day (cron = "0 0 1 * *?")

Execute @ scheduled every 3 minutes (cron = "0 0 / 3 * *?")

So how on earth did this come out?

Official api

In fact, the cron expression is usually followed by 6 characters separated by spaces, and each field identifies a meaning:
second minuters hours dayOfMonth month dayOfWeek

Serial number field Characters that can appear
1 second , - * / integer from 0 to 59
2 minuters , - * / integer from 0 to 59
3 hours , - * / integer from 0 to 23
4 dayOfMonth , - * / ? Integer from w to l 31
5 month , - * / integer from 1 to 12
6 dayOfWeek , - * / ? An integer from L #1 to 7 (or SUN to SAT, 1 for Sunday and 2 for Monday)
Serial number character meaning
1 , Indicates the enumeration value. For example, in the minuters field, 2,10 indicates that it is triggered once in 2 minutes and 10 minutes respectively
2 - Indicates the range. For example, in the minuters domain, using 2-10 means starting every minute from 2 minutes to 10 minutes
3 * Indicates any value. For example, if * is used in the minuters field, it means that it will be triggered every minute
4 / Indicates the start / step size. For example, using 2 / 10 in the minuters field indicates that it is triggered every ten minutes from 2 minutes (2, 12, 22, 32, 42, 52). If the start value is set to * is equivalent to 0
5 ? It means that it is not set. It usually appears in two interacting fields (dayOfMonth and dayOfWeek). When the date is set, the week can only be?
6 L Indicates the last value. For example, the date indicates the 30th, 31st, 29th and 28th of the last day of the month; In the middle of the week, 6L means the last Friday of the month
7 W Indicates that valid working days (and Monday to Friday) can only appear in the date field. The system will trigger the event on the latest valid working day from the specified date. For example: 5W, if it is Saturday, it will be triggered on the nearest working day, that is, Friday, that is, the 4th. If the 5th is Sunday, it will be triggered on the next Monday, that is, the 6th. Note that it will not cross the month
8 # Indicates the day of the week, which can only be used in the week. For example: 4#2 indicates the second Wednesday of a month

Example:

cron expressions meaning
0 0 10,14,16 * * ? Every day at 10 a.m., 2 p.m. and 4 p.m
0 0/30 9-17 * * ? Every 30 minutes between 9 a.m. and 5 p.m
0 0 12 ? * WED It means 12 noon every Wednesday
0 0 12 * * ? At 12 noon every day
0 15 10 ? * * Every morning at 10:15
0 15 10 * * ? 2005 At 10:15 a.m. every day in 2005 (usually without years)
0 * 14 * * ? Every minute between 2 p.m. and 2:59 p.m
0 0/5 14 * * ? Every 5 minutes between 2 p.m. and 2:59 p.m
0 0/5 14,18 * * ? Every 5 minutes between 2 p.m. and 2:59 p.m. and between 6 p.m. and 6:59 p.m
0 0-5 14 * * ? Every minute between 2 p.m. and 2:05 p.m

Topics: Java Spring Boot