一、Mysql实现
-
查看event是否开启
如果不做这一步,事件创建后,
将会发现‘事件计划已关闭。事件只能在服务器启动并开启事件计划时才能处理。'的警告。
通过下列语句l爱查询event是否开启
show variables like '%sche%';
通过执行下列语句,来开启event_scheduler
set global event_scheduler =1;
-
新建存储过程
可以从navicat界面的‘函数’进入,也可以直接用查询建立。
查询建立:
CREATE PROCEDURE test () BEGIN update profile set single=19 where id = any (SELECT id FROM (select tmp.* from profile tmp WHERE birthday<=NOW()) as p); END;
界面中建立:
命名为test
BEGIN update profile set single=19 where id = any (SELECT id FROM (select tmp.* from profile tmp WHERE birthday<=NOW()) as p); END
这个地方要注意,同一个表不能作为本表的subquery,所以就从临时表里把数据取出来,这样就不是同查同更。
-
新建Event
从界面中的‘事件’进入
定义中就直接写
call test();
计划里,基本上看看就知道什么意思
不过starts和ends的时间格式应该是:2012-12-11 19:06:00
我设成20秒一更新
经测试成功
二、java实现
1、
package com.gdzy.CPZX.util;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class oneTimer implements ServletContextListener{
private Timer timer = null;
//时间间隔
private static long INTERVALTIME = 1 * 60 * 1000 ;
public oneTimer() {
Calendar calendar = Calendar.getInstance();
/*** 定制每日0:00执行方法 ***/
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date=calendar.getTime(); //第一次执行定时任务的时间
//如果第一次执行定时任务的时间 小于 当前的时间
//此时要在 第一次执行定时任务的时间 加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。
if (date.before(new Date())) {
date = this.addDay(date, 1);
}
timer = new Timer(true);
timer.schedule(new MyJob(), date, INTERVALTIME);
}
//定时任务要执行的方法
class MyJob extends TimerTask {
public void run() {
System.out.println("定时任务!"+new Date());
}
}
public void contextInitialized(ServletContextEvent event) {
new oneTimer();
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
}
public Date addDay(Date date, int num) {
Calendar startDT = Calendar.getInstance();
startDT.setTime(date);
startDT.add(Calendar.DAY_OF_MONTH, num);
return startDT.getTime();
}
}
web.xml里需加入
<listener>
<listener-class>com.gdzy.CPZX.util.oneTimer</listener-class>
</listener>
2、直接使用spring的注解@Scheduled
package com.example.demo.schedule;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyStaticTask {
//注解配置定时任务
@Autowired
private UserService userService;
@Scheduled(cron = "0/10 * * * * ?")
public void doTask(){
System.out.println("执行了MyStaticTask,时间为:"+new Date(System.currentTimeMillis()));
}
@Scheduled(cron = "* 0/1 * * * ?")
public void doInsertTask(){
User user = new User();
user.setuAge(25);
user.setuName("lk");
user.setuDesc("ss");
userService.insert(user);
System.out.println("doInsertTask,时间为:"+new Date(System.currentTimeMillis()));
}
}
使用spring注解时要在在启动类上加上@EnableScheduling 这个注解 否则定时任务不起作用