最近在写一个纯java项目,用到了定时任务,发现java本身的定时任务使用很复杂,所以改造了一下,这里做个记录。
改造成在方法体上方加注解的形式,类似于spring-boot的@Scheduled(cron = "0 0 0 * * ?")注解的方式。使用方法,@QuartzTime(delayTime = 3,unit = TimeUnit.MINUTES)第一个参数为数量,第二个参数为时间单位,这个例子代表3分钟。
主要执行类:
public class TimeUtil {
private static Logger log = Logger.getLogger(TimeUtil.class);
private static ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
public static void startJob(final Class clazz){
Method [] methods = clazz.getDeclaredMethods();
for (final Method m : methods) {
if(m.isAnnotationPresent(QuartzTime.class)){
QuartzTime qt = m.getAnnotation(QuartzTime.class);
if (qt != null) {
Runnable r = new Runnable() {
public void run() {
try {
m.invoke(clazz.newInstance());
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException
| InstantiationException e) {
e.printStackTrace();
}
}
};
log.info("创建作业=> [作业方法:" +clazz.getName() +"."+ m.getName() + "()] ");
service.scheduleAtFixedRate(r, 0, qt.delayTime(), qt.unit());
}
}
}
}
@QuartzTime(delayTime = 2)
public void test(){
System.out.println("执行了!");
}
@QuartzTime(delayTime = 2)
public void test1(){
System.out.println("执行第二个了!");
}
}
注解类:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface QuartzTime {
/**
* 延期时间
* @return
*/
int delayTime();
/**
* 单位
* @return
*/
TimeUnit unit() default TimeUnit.SECONDS;
}
使用方法:
需要定时执行的任务上加@QuartzTime注解,然后在main方法中执行TimeUtil.startJob(App.class);