Schedule.java 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package jnpf.base.util.job;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import jnpf.base.UserInfo;
  4. import jnpf.base.entity.ScheduleNewEntity;
  5. import jnpf.base.model.schedule.ScheduleJobModel;
  6. import jnpf.base.service.ScheduleNewService;
  7. import jnpf.config.ConfigValueUtil;
  8. import jnpf.database.util.TenantDataSourceUtil;
  9. import jnpf.exception.TenantInvalidException;
  10. import jnpf.util.RedisUtil;
  11. import jnpf.util.StringUtil;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.quartz.DisallowConcurrentExecution;
  14. import org.quartz.JobExecutionContext;
  15. import org.quartz.JobExecutionException;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.data.redis.core.RedisTemplate;
  18. import org.springframework.scheduling.quartz.QuartzJobBean;
  19. import java.util.List;
  20. import java.util.concurrent.TimeUnit;
  21. @Slf4j
  22. @DisallowConcurrentExecution
  23. public class Schedule extends QuartzJobBean {
  24. @Autowired
  25. private RedisUtil redisUtil;
  26. @Autowired
  27. private ScheduleNewService scheduleNewService;
  28. @Autowired
  29. private RedisTemplate redisTemplate;
  30. @Autowired
  31. private ScheduleJobUtil scheduleJobUtil;
  32. @Autowired
  33. private ConfigValueUtil configValueUtil;
  34. @Override
  35. protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
  36. List<ScheduleJobModel> listRedis = scheduleJobUtil.getListRedis(redisUtil);
  37. for (ScheduleJobModel jobModel : listRedis) {
  38. String id = jobModel.getId();
  39. boolean useSuccess = redisTemplate.opsForValue().setIfAbsent(ScheduleJobUtil.WORKTIMEOUT_REDIS_KEY + "_key:" + id, System.currentTimeMillis(), 100, TimeUnit.SECONDS);
  40. if (!useSuccess) continue;
  41. UserInfo userInfo = jobModel.getUserInfo();
  42. if (configValueUtil.isMultiTenancy()) {
  43. try {
  44. TenantDataSourceUtil.switchTenant(userInfo.getTenantId());
  45. }catch (TenantInvalidException e){
  46. // 租户无效 删除任务
  47. log.error("Schedule, 租户无效, 删除任务:{}", userInfo.getTenantId());
  48. redisUtil.removeHash(ScheduleJobUtil.WORKTIMEOUT_REDIS_KEY, id);
  49. }
  50. }
  51. ScheduleNewEntity info = scheduleNewService.getInfo(id);
  52. boolean msg = info != null && System.currentTimeMillis() >= jobModel.getScheduleTime().getTime();
  53. if (msg) {
  54. scheduleNewService.scheduleMessage(jobModel);
  55. }
  56. boolean delete = (ObjectUtil.isNull(info) || msg);
  57. if (delete) {
  58. redisUtil.removeHash(ScheduleJobUtil.WORKTIMEOUT_REDIS_KEY, id);
  59. }
  60. }
  61. }
  62. }