集群定时任务执行多次

来源:互联网 发布:java局部变量重复 编辑:程序博客网 时间:2024/05/17 21:42

处理集群定时任务多次执行新增可能存在重复数据问题:
第一种就是下面的方法,利用redis
第二种建立数据库唯一约束(会执行多次)
还有quartz等等

设置失效时间为定时任务结束时间至下次定时任务执行时间之间就行,使用setnx方法设置锁。

public static boolean setStringNx(String key,int seconds,String value) {        Jedis jedis = null;        try {            jedis = sentinelPool.getResource();            if (1 == jedis.setnx(key, value)) {                jedis.expire(key, seconds);                return true;            }        } catch (Exception e) {            throw e;        } finally {            if (jedis != null){                jedis.close();            }        }        return false;    }

定时任务执行时间为半小时一次,设置redisKey失效时间为10分钟

public void getSaler() {    try {        if(RedisUtil.setStringNx("TASK_GETSALER", 60 * 10, "on")){            doJob();        }    } catch (Exception e) {        LogUtil.e("异常", e);    }}
原创粉丝点击