公司最近分了一个项目,有一个需求让每天和每月定时执行sql的脚本,本来打算用线程池,但是看到springboot支持Scheduled定时任务,并且开发简单,就拿来用了
具体代码如下:
在启动类上加注解
@SpringBootApplication
@EnableScheduling
public class ManageApplication {
public static void main(String[] args) {
SpringApplication.run(ManageApplication.class, args);
}
}
执行的方法
@Component
@Transactional
public class ProductTask{
private final Log logger = LogFactory.getLog(getClass());
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Scheduled(cron = "0 1 0 * * ?")
public void runDayBatch() {
try {
Connection conn= DriverManager.getConnection(url,username,password);
String sql ="执行的sql";
PreparedStatement ps2 = conn.prepareStatement(sql);
ps2.addBatch();
ps2.executeBatch();
ps2.close();
logger.info("每日定时采集成功......");
conn.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("每日定时采集失败.....");
}
}
@Scheduled(cron = "0 0 0 1 * ?")
public void runMonthBatch() {
try {
Connection conn= DriverManager.getConnection(url,username,password);
String sql ="执行的sql";
PreparedStatement ps1 = conn.prepareStatement(sql);
ps1.addBatch();
ps1.executeBatch();
ps1.close();
logger.info("每月定时采集成功......");
conn.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("每月定时采集失败.....");
}
}
}
@Scheduled注解里配置的执行日期时间,具体规范各位可以自行去百度,网上有很详细的解释