1. public class TimeHashWheel {
    2. // 任务存储
    3. private Map<Integer, List<Task>> taskMap;
    4. // 每轮时长
    5. private int duration;
    6. // 单期耗时
    7. private int tick;
    8. private volatile boolean start;
    9. public static void main(String[] args) {
    10. TimeHashWheel wheel = new TimeHashWheel(6000, 100);
    11. wheel.start();
    12. for (int i = 0; i < 100; i++) {
    13. String date = "task_no_" + i;
    14. int delay = (int) (Math.random() * 3 * 6000);
    15. wheel.addTask(date, delay);
    16. System.out.println("insert task : " + date + ", delay by : " + delay);
    17. }
    18. }
    19. public TimeHashWheel(int duration, int tick) {
    20. this.taskMap = new HashMap<>(duration / tick);
    21. this.duration = duration;
    22. this.tick = tick;
    23. this.start = true;
    24. }
    25. public void addTask(String data, int delay) {
    26. int bucket = (delay % duration) / tick;
    27. int round = delay / duration;
    28. taskMap.computeIfAbsent(bucket, k -> new ArrayList<>());
    29. taskMap.get(bucket).add(new Task(data, round));
    30. }
    31. public void start() {
    32. Executors.newSingleThreadExecutor().execute(() -> {
    33. try {
    34. int begin = 0;
    35. while (start) {
    36. if ((begin == (duration / tick))) {
    37. System.out.println("tick to next round ---- ");
    38. begin = 0;
    39. }
    40. System.out.println("tick to :" + (begin));
    41. List<Task> list = taskMap.get(begin++);
    42. System.out.println("found bucket has " + (list == null ? 0 : list.size())
    43. + " task");
    44. if (!CollectionUtils.isEmpty(list)) {
    45. Iterator<Task> it = list.iterator();
    46. while (it.hasNext()) {
    47. Task task = it.next();
    48. if (task.round > 0) {
    49. task.round--;
    50. } else {
    51. System.out.println("============= execute task : " + task.data);
    52. it.remove();
    53. }
    54. }
    55. }
    56. TimeUnit.MILLISECONDS.sleep(tick);
    57. }
    58. } catch (Exception e) {
    59. e.printStackTrace();
    60. }
    61. });
    62. }
    63. class Task {
    64. private String data;
    65. private int round;
    66. public Task(String data, int round) {
    67. this.data = data;
    68. this.round = round;
    69. }
    70. }
    71. }