使用Java的Timer处理周期性任务

时间:2021-07-11 04:54:28
package timer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Timer;
import java.util.TimerTask; import util.DBUtil; public class TimerTest {
public static void main(String[] args) {
Timer timer = new Timer();
// 延迟1秒钟,每5秒钟执行一次
timer.schedule(new MyTask(), 1000, 5000);
}
} class MyTask extends TimerTask{ // 任务内容
@Override
public void run() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select status from jiankong_table where service_name='duomeidai-web' and "
+ "service_time = DATE_FORMA(NOW(),'%Y-%m-%d') order by service_time desc limit 1";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("status"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtil.close(conn, stmt, rs);
}
}
}

以上先睹为快。

如果使用TimerTask或者定时任务,后续进行补贴!