Hutool + Cron 实现定时任务

539 阅读1分钟

依赖

<!--hutool工具包-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.14</version>
</dependency>

实例

方法参考: plus.hutool.cn/docs/#/cron…

主要逻辑

// 管理员点击封号按钮

if(用户正常){
   
   封号1天;
    
   设置定时器,1天后解封;

}

if(管理员点击解封){

    直接更新数据库,不执行1日后的定时器;
    
}

其中,开启定时器方法为:CronUtil.start();

解封用户的代码为:

 CronUtil.schedule(
     EMPLOYEE_DISABLE_LIMIT+"/"+EMPLOYEE_DISABLE_LIMIT+" * * * * ?",
     (Task) () -> enableUser(id));
  }
  
  private void enableUser(Long id){ 
      Long updateId = BaseContext.get(); 
      LambdaUpdateWrapper<Employee> wrapper = new LambdaUpdateWrapper<>(); wrapper.eq(Employee::getId,id); 
      Employee employee = new Employee().setStatus(1).setUpdateUser(updateId); employeeService.update(employee,wrapper);
      CronUtil.stop(); 
    }

CronUtil.schedule(),第一个参数为cron表达式,设置更新频率,第二个参数为每次更新需要做的事情。

关闭定时器的方法为CronUtil.stop();

注:cron可以看作一个循环周期函数,会一直执行下去;若需要中途退出,可使用CronUtil.stop()终止循环。

语法不需要特意学习,有自动生成工具:cron.qqe2.com/

完整代码

//更新员工状态
@ResponseBody
@PutMapping("/employee")
@SaCheckPermission("admin:addEmployee")
@CacheEvict(value={"employeeCache","RoleList","PermissionList"},allEntries = true)
@Transactional
public Result updateStatus( @RequestBody Employee employee) {

    Long id = employee.getId();
    RoleMapping roleMapping = new RoleMapping();
    //封禁操作
    Integer status = employee.getStatus();
    if(status!=null){
        //封禁操作
        if(status==0){
            // 先踢下线后封禁
            // 先踢下线
            StpUtil.kickout(id);
            // 再封禁账号
            StpUtil.disable(id,EMPLOYEE_DISABLE_LIMIT);

            CronUtil.start(true);
            //封禁时间到期后解封
            CronUtil.schedule(EMPLOYEE_DISABLE_LIMIT+"/"+EMPLOYEE_DISABLE_LIMIT+" * * * * ?", (Task) () -> enableUser(id));

        }else {
            // 解除封禁
            StpUtil.untieDisable(id);
            CronUtil.stop();
        }
        employee.setStatus(status);
        
    }else{
        Integer isEdit = employee.getIsEdit();
        roleMapping.setRoleId(id);
        roleMapping.setIsEdit(isEdit);

        LambdaQueryWrapper<RoleMapping> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMapping::getRoleId,id);
        roleMappingService.update(roleMapping,wrapper);

    }

    //拿新的状态值
    log.info("更新的用户信息为:"+employee);
    //员工信息更新后,会自动清除缓存
    employeeService.updateById(employee);
    return Result.success(employee);
}

private void enableUser(Long id){
    Long updateId = BaseContext.get();

    LambdaUpdateWrapper<Employee> wrapper = new LambdaUpdateWrapper<>();
    wrapper.eq(Employee::getId,id);
    Employee employee = new Employee().setStatus(1).setUpdateUser(updateId);
    employeeService.update(employee,wrapper);
    CronUtil.stop();
}