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