SpringBoot定时执行脚本

需求:每天定时执行*.sql脚本

1.添加定时任务

这个只要springboot启动类加 注解

@EnableScheduling

然后在自己的方法上加定时注解 (例如下面每晚0点0分20秒执行)

@Scheduled(cron = "20 0 0 ? * *")

2.读取脚本并执行

脚本放在执行服务器文件夹下,可以直接读取文件夹下所有*.sql

File file = new File("/home/sqls");
if (file.exists()) {
	String[] list = file.list();
	for (String name : list) {
		File f = new File("/home/sqls", name);
		if (f.isFile()) {
			// 执行这个脚本
            this.executeScript("/home/sqls/"+name)
		}
	}
}

为了更灵活,可以把需要执行的脚本记录在数据库,每个脚本都可以加是否执行状态和执行组等

3.执行脚本方法

 @Autowired
 private DataSource dataSource;

public void executeScript(String filePath){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }

        ScriptRunner runner = new ScriptRunner(conn);
        runner.setEscapeProcessing(false);
        runner.setSendFullScript(true);
        try {
            runner.runScript(new InputStreamReader(new FileInputStream(filePath), "GBK"));
        }
        catch (IOException e) {
            log.warn("########### run sql script error #############{}", filePath);
            e.printStackTrace();
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值