1.定义一个接口
package com.zsp.quartz.service;
public interface ScheduledService {
void setInfo();
}
2.定义实现类
package com.zsp.quartz.service.impl;
import com.alibaba.fastjson.JSON;
import com.zsp.quartz.entity.User;
import com.zsp.quartz.service.ScheduledService;
import com.zsp.quartz.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.PreDestroy;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class ScheduledServiceImpl implements ScheduledService, InitializingBean {
@Autowired
UserService userService;
// 创建线程池
private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
// 1.原始接口方法
@Override
@Async
public void setInfo() {
for (int i = 0; i < 100; i++) {
System.out.println("接口的方法" + i);
}
}
// 1.实现InitializingBean的方法
@Override
public void afterPropertiesSet() throws Exception {
executorService.scheduleAtFixedRate(this::scheduleProcessUser, 10, 10, TimeUnit.SECONDS);
}
// 2.释放线程池资源的方法
// PreDestroy注解:Spring优雅的退出
@PreDestroy
public void destroy() {
try {
executorService.shutdown();
} catch (Exception e) {
}
}
// 3.自己定义的线程池中要执行的方法
public void scheduleProcessUser() {
while (true) {
User user = null;
try {
user = userService.getById(2);
Thread.sleep(3000);
log.info("用户角色信息同步:{}", JSON.toJSONString(user));
} catch (Exception e) {
log.error("处理用户角色信息同步异常:{}", JSON.toJSONString(user), e);
}
}
}
}
控制台打印