简单重试逻辑

应用场景

  1. 定时任务重试
  2. 回调业务时的延时计算

定义工具类

public int returnTimeInterval(int num) {
    int timeInterval[] = {0, 5, 5,
            15, 15,
            30, 60, 180, 1800,
            3600, 3600, 3600, 3600, 3600,
            3600, 3600, 3600, 3600, 3600,
            3600, 3600, 3600, 3600, 3600,
            3600, 3600, 3600, 3600,
            3600, 3600, 3600, 3600, 3600};
    if (num < timeInterval.length) {
        return timeInterval[num];
    } else {
        return 36000000;
    }
}

使用方法

t.setNextNotifyTime(System.currentTimeMillis() + returnTimeInterval(t.getNotifyNum()) * 1000);
t.setNotifyNum(t.getNotifyNum() + 1);

举例:

简单的基于数据库的任务处理方法,当任务数量不太多,也不太关注是否及时时可以使用

任务状态枚举类

public enum TaskStatus {
    NEW(0),
    SUCCSS(1),
    FAIL(2),
    ;

    private int v;

    public static TaskStatus vOf(int v) {
        for (TaskStatus value : TaskStatus.values()) {
            if (v == value.v) {
                return value;
            }
        }
        return null;
    }

    TaskStatus(int v) {
        this.v = v;
    }

    public int getV() {
        return v;
    }
}

任务存储

表结构(任务相关):id, notify_state, notify_num, next_notify_time, max_notify_num, finish_time

任务拉取

// SQL查询语句
select id
from t_xx_task
where notify_num <![CDATA[>=]]> #{startNum} and notify_num <![CDATA[<]]> #{endNum}
and next_notify_time <![CDATA[<=]]> #{currentTime} and notify_state != #{notStates}

任务队列1:startNum = 0, endNum = 3, currentTime = 当前时间, notStates = 1 
任务队列2:startNum = 3, endNum = 32, currentTime = 当前时间, notStates = 1 

任务执行

1. 基于ID锁定表中记录
2. 执行
3. 任务队列1执行,当没有任务时,暂停500ms
4. 任务队列2执行,当没有任务时,暂停10s

This entry was posted in 编程工具. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.