shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.walker.infrastructure.scheduler;
 
import com.walker.infrastructure.core.NestedRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * 抽象定时任务定义基类,子类实现具体执行任务,同时可以设置间隔时间和延时时间
 * @author MikeShi
 *
 */
public abstract class AbstractTimedTask implements TimedTask {
 
    protected transient Logger logger = LoggerFactory.getLogger(this.getClass());
    
    //最小间隔时间,默认5秒
    private static final long TIMED_MIN_PERIOD = 5000;
    
    //最小延时时间,即系统启动后多长时间后开始运行任务,默认30秒钟
    private static final long TIMED_MIN_DELAY = 30000;
    
    private static final int MAX_ERROR_COUNT = 10;
    
    private int errorCount = 0;
    
    private long delay = 5000;
    private long period = 0;
    
    public long getDelay() {
        // TODO Auto-generated method stub
        if(delay == 0){
            delay = TIMED_MIN_DELAY;
        }
        return delay;
    }
 
    public long getPeriod() {
        // TODO Auto-generated method stub
        if(period < 0){
            throw new NullPointerException("period must be set in TimedTask! It is more than 0.");
        } else if(period > 0 && period < TIMED_MIN_PERIOD){
            throw new NestedRuntimeException("period must more than" + TIMED_MIN_PERIOD/1000 + " seconds in TimedTask!");
        }
        return period;
    }
 
    public void setDelay(long delays) {
        // TODO Auto-generated method stub
        if(delays < TIMED_MIN_DELAY){
            this.delay = TIMED_MIN_DELAY;
        } else
            this.delay = delays;
    }
 
    public void setPeriod(long periods) {
        // TODO Auto-generated method stub
        if(periods > 0 && periods < TIMED_MIN_PERIOD){
            this.period = TIMED_MIN_PERIOD;
        } else
            this.period = periods;
    }
 
    public void run() {
        // TODO Auto-generated method stub
        if(period == 0){
            logger.debug("任务执行忽略,设置间隔为0");
            return;
        }
        
        if(errorCount > MAX_ERROR_COUNT){
            //执行通知事件:告知管理员系统定时任务错误执行了最大值
            //eventPublisher.notify();
            logger.debug("//*************定时任务执行错误,已超出错误最大值!");
        }
        
        try {
            execute();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.warn("execute error in TimedTask: " + this.getClass().getName());
            logger.error(e.getMessage());
            errorCount++;
        }
    }
 
    public abstract void execute() throws Exception;
}