SpringBoot框架中利用定时任务实现自动备份数据库

主要思路是创建一个定时任务执行自动备份的语句。为了我们随时能够修改定时任务的执行周期,通常我们在数据库建一张存储 cron 语句的表,每次执行完定时任务后到这张表里面查询新的 cron 语句。

完整代码如下:

package com.qiao;

import com.qiao.dao.CronRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

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

@Configuration
@EnableScheduling
public class autoBackup implements SchedulingConfigurer {
     

    @Autowired
    private CronRepository cronRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
     

        scheduledTaskRegistrar.addTriggerTask(
                () -> jdbcTemplate.execute("CALL CSVWRITE('~/.h2/" + sdf.format(new Date()) +".csv', 'SELECT * FROM information')"),
                triggerContext -> {
     
                    String cron = cronRepository.getOne(1L).getCron();
                    if (StringUtils.isEmpty(cron)) {
     
                        throw new IllegalArgumentException("Cron表达式错误!");
                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );

    }
}

你可能感兴趣的:(数据库,spring)