需求:每天定时执行*.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();
}
}