Spring Boot | Use @Scheduled annotation to backup database regularly

Regularly back up the database. The demonstration interval in this example is 2 seconds. The database is not configured in the properties in the project (note the two notes in the Main class)

Main class

@SpringBootApplication(exclude= {
    
    DataSourceAutoConfiguration.class})
@EnableScheduling
public class TaskApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(TaskApplication.class, args);
    }

}

One, under the windows environment

package com.springboot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
@Slf4j
public class task {
    
    
    @Scheduled(cron = "*/2 * * * * ?")
    public void dump() throws Exception {
    
    
        log.info("备份数据库");
        String backName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        dataBaseDump("localhost", "3306", "root", "123456", "excel", backName);
    }

    //mysqldump -hlocalhost -P3306 -uroot -p123456 db > E:/back.sql
    //备份
    public static void dataBaseDump(String host, String port, String username, String password, String databasename, String sqlname) throws Exception {
    
    
        File file = new File("E:\\test");
        if (!file.exists()) {
    
    
            file.mkdir();
        }
        File datafile = new File(file + File.separator + sqlname + ".sql");
        if (datafile.exists()) {
    
    
            System.out.println(sqlname + "文件名已存在,请更换");
            return;
        }
        //拼接cmd命令
        Process exec = Runtime.getRuntime().exec("cmd /c mysqldump -h" + host + " -P" + port + " -u " + username + " -p" + password + " " + databasename + " > " + datafile);
        if (exec.waitFor() == 0) {
    
    
            System.out.println("数据库备份成功,备份路径为:" + datafile);
        }
    }
}

Insert picture description here

Two, under the linux environment

package com.springboot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
@Slf4j
public class task {
    
    
    @Scheduled(cron = "*/2 * * * * ?")
    public void dump() throws Exception {
    
    
        log.info("备份数据库");
        String backName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        dataBaseDump("localhost", "3306", "root", "123456", "excel", backName);
    }

    //mysqldump -hlocalhost -P3306 -uroot -p123456 db > E:/back.sql
    //备份
    public static void dataBaseDump(String host, String port, String username, String password, String databasename, String sqlname) throws Exception {
    
    
        File file = new File("E:\\test");
        if (!file.exists()) {
    
    
            file.mkdir();
        }
        File datafile = new File(file + File.separator + sqlname + ".sql");
        if (datafile.exists()) {
    
    
            System.out.println(sqlname + "文件名已存在,请更换");
            return;
        }
        //拼接cmd命令
        Process exec = Runtime.getRuntime().exec("/bin/sh -c mysqldump -h" + host + " -P" + port + " -u " + username + " -p" + password + " " + databasename + " > " + datafile);
        if (exec.waitFor() == 0) {
    
    
            System.out.println("数据库备份成功,备份路径为:" + datafile);
        }
    }
}

Three, detailed explanation of cron expression

1. Structure

Corn from left to right (separated by spaces): seconds, minutes, hours, month, day, month, week, day, year

2. The meaning of each field

Field allowance Special characters allowed
Seconds (Seconds) Integer from 0 to 59 ,-* / Four characters
分(Minutes) Integer from 0 to 59 ,-* / Four characters
Hours Integer from 0 to 23 ,-* / Four characters
Date (DayofMonth) An integer from 1 to 31 (but you need to consider the number of days in your month) ,- *? / LWC eight characters
Month An integer from 1 to 12 or JAN-DEC ,-* / Four characters
Week (DayofWeek) An integer from 1 to 7 or SUN-SAT (1=SUN) ,-*? / LC # eight characters
Year (optional, leave blank) (Year)1970~2099 ,-* / Four characters

3. Matters needing attention

Each field uses numbers, but the following special characters can also appear, their meanings are:
(1) *: indicates any value that matches the field. If you use * in the Minutes field, it means that an event will be triggered every minute.

(2) ?: It can only be used in DayofMonth and DayofWeek domains. It also matches any value of the domain, but it does not. Because DayofMonth and DayofWeek will affect each other. For example, if you want to trigger scheduling on the 20th of each month, no matter what day of the week the 20th is, you can only use the following notation: 13 13 15 20 * ?, the last digit can only be used? , And you cannot use *. If you use *, it will trigger regardless of the day of the week, which is actually not the case.

(3) -: Indicates the range. For example, using 5-20 in the Minutes field means that it will be triggered every minute from 5 minutes to 20 minutes

(4) /: Indicates that the trigger starts at the start time, and then triggers once every fixed time. For example, using 5/20 in the Minutes field means that it will be triggered once every 5 minutes, while 25, 45, etc. will be triggered once.

(5) ,: Indicates to list enumerated values. For example: using 5,20 in the Minutes field means it will be triggered every minute at 5 and 20 minutes.

(6) L: Indicates that at the end, it can only appear in the DayofWeek and DayofMonth fields. If 5L is used in the DayofWeek domain, it means it will be triggered on the last Thursday.

(7) W: Indicates valid working days (Monday to Friday), which can only appear in the DayofMonth domain, and the system will trigger the event on the nearest valid working day from the specified date. For example: using 5W in DayofMonth, if the 5th is Saturday, it will be triggered on the nearest working day: Friday, that is, the 4th. If the 5th is Sunday, it will be triggered on the 6th (Monday); if the 5th is one day from Monday to Friday, it will be triggered on the 5th. Another point, W's recent search will not span the month.

(8) LW: These two characters can be used together to indicate the last working day of a month, that is, the last Friday.

(9) #: Used to determine the day of the week of each month, which can only appear in the DayofWeek domain. For example, 4#2 means the second Wednesday of a certain month.

4. Examples of commonly used expressions

(0) 0/20 * * * * ?means to adjust the task every 20 seconds
(1) 0 0 2 1 * ?means to adjust the task at 2 am on the 1st of each month
(2) 0 15 10 ? *MON-FRI means to execute the task at 10:15 am every day from Monday to Friday
(3) 0 15 10 ? 6L 2002-2006means 2002-2006 The last Friday of each month of the year is executed at 10:15 am
(4) 0 0 10,14,16 * * ?10 am, 2 pm, and 4 pm every day
(5) 0 0/30 9-17 * * ?every half an hour during working hours from 9 to 5
(6) 0 0 12 ? * WEDmeans noon every Wednesday 12 o’clock
(7) 0 0 12 * * ?every day at 12 noon trigger
(8) 0 15 10 ? * *every day at 10:15 am trigger
(9) 0 15 10 * * ?every day at 10:15 am trigger
(10) 0 15 10 * * ? *every day at 10:15 am trigger
(11) 0 15 10 * * ? 2005every day in 2005 at 10:15 am trigger
( 12) 0 * 14 * * ?Trigger every 1 minute between 2 pm and 2:59 pm every day
(13) 0 0/5 14 * * ?Trigger every 5 minutes between 2 pm and 2:55 pm every day
(14) Trigger every 5 minutes 0 0/5 14,18 * * ?between 2 pm and 2:55 pm every day And every 5 minutes from 6 pm to 6:55 pm
(15) 0 0-5 14 * * ?every 1 minute from 2 pm to 2:05 pm every day
(16) 0 10,44 14 ? 3 WED2:10 pm and 2:44 pm on Wednesday in March each year trigger
(17) 0 15 10 ? * MON-FRITrigger at 10:15 am from Monday to Friday
(18) Trigger at 10:15 am on the 0 15 10 15 * ?15th of each month
(19) Trigger at 10:15 am on the 0 15 10 L * ?last day of each month
(20) Trigger 0 15 10 ? * 6Lat 10 am on the last Friday of each month : 15 trigger
(21) from 0 15 10 ? * 6L 2002-20052002 to 2005, trigger at 10:15 am on the last Friday of each month
(22) trigger at 10:15 am 0 15 10 ? * 6#3on the third Friday of each month

Guess you like

Origin blog.csdn.net/y1534414425/article/details/106801521