Springboot 项目启动另起线程

背景

有时候我们需要在项目启动创建一个线程去定时处理一些数据之类的,当然也可以用类似xxl-job的定时任务来处理,这里我们使用项目启动的同时开启一个线程的方式

实现

@Component
@Slf4j
public class ClearThread implements DisposableBean,Runnable {

    private Thread thread;
    private volatile boolean someCondition = true;

    private final ClearService clearService;

    private final ClearJobDao clearJobDao;
	// dao 和service注入
    @Autowired
    public ClearThread(ClearService clearService, ClearJobDao clearJobDao) {
        this.clearService = clearService;
        this.clearJobDao = clearJobDao;
        this.thread = new Thread(this);
        this.thread.start();
        log.info("线程启动");
    }

    @Override
    public void run() {
        while (someCondition) {
            // 数据库调用
            Integer customerId = clearJobDao.getCustomerId();
            if (customerId == null) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
            	// 数据库调用
                int updateFlag = clearJobDao.updateFlag(customerId);
                if (updateFlag < 1) {
                    return;
                }
                // 数据库调用
                clearService.clear(Lists.newArrayList(customerId));
                // 数据库调用
                clearJobDao.deleteCustomerId(customerId);
            }
        }

    }




    @Override
    public void destroy() throws Exception {
        someCondition = false;
    }
}

你可能感兴趣的:(Spring,Boot,spring,boot)