java定时任务每晚凌晨三点将sc_order_distribute表的数据备份到sc_order_distribute_back表中,然后根据今天时间和creat_time之间的时间相差为30天,将这些数据的del更改为10(之前为0),将del为10的数据全部删除,核对数据
时间: 2024-05-03 18:23:24 浏览: 115
代码如下:
```
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class BackupAndDeleteData {
public static void main(String[] args) {
Timer timer = new Timer();
// 设置定时任务开始的时间
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 3);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
// 如果当前时间已经过了3点,则定时任务开始时间为明天的3点
if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_YEAR, 1);
}
// 定时任务:每天凌晨3点备份数据并删除过期数据
timer.schedule(new TimerTask() {
@Override
public void run() {
backupData();
deleteExpiredData();
}
}, calendar.getTime(), 24 * 60 * 60 * 1000);
}
// 数据备份方法
public static void backupData() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDate = sdf.format(new Date());
String backupSql = "INSERT INTO sc_order_distribute_back SELECT * FROM sc_order_distribute";
// 执行备份sql语句
// ...
System.out.println(currentDate + ":数据备份完成");
}
// 删除过期数据方法
public static void deleteExpiredData() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, -30);
String expiredDate = sdf.format(calendar.getTime());
String updateSql = "UPDATE sc_order_distribute SET del=10 WHERE creat_time < '" + expiredDate + "' AND del=0";
String deleteSql = "DELETE FROM sc_order_distribute WHERE del=10";
// 执行更新和删除sql语句
// ...
System.out.println("删除过期数据完成");
// 核对数据
// ...
System.out.println("数据核对完成");
}
}
```
阅读全文