Class TaskKit

java.lang.Object
com.iohao.net.common.kit.concurrent.TaskKit

public class TaskKit extends Object
Internal utility class for task consumption; developers should NOT use it for time-consuming I/O tasks.

example - Execute task using another thread

TaskKit.execute(()->{
    log.info("Your logic");
});

example - netty TimerTask
// Execute after 3 seconds
TaskKit.newTimeout(new TimerTask() {
    @Override
    public void run(Timeout timeout) {
        log.info("3-newTimeout : {}", timeout);
    }
}, 3, TimeUnit.SECONDS);

example - TaskListener callback. Internally uses HashedWheelTimer to simulate ScheduledExecutorService scheduling
// Execute only once, after 2 seconds
TaskKit.runOnce(() -> log.info("2 Seconds"), 2, TimeUnit.SECONDS);
// Execute only once, after 1 minute
TaskKit.runOnce(() -> log.info("1 Minute"), 1, TimeUnit.MINUTES)
// Execute only once, after 500, 800 milliseconds
TaskKit.runOnce(() -> log.info("500 delayMilliseconds"), 500);
TaskKit.runOnce(() -> log.info("800 delayMilliseconds"), 800);

// Called every minute
TaskKit.runIntervalMinute(() -> log.info("tick 1 Minute"), 1);
// Called every 2 minutes
TaskKit.runIntervalMinute(() -> log.info("tick 2 Minute"), 2);

// Called every 2 seconds
TaskKit.runInterval(() -> log.info("tick 2 Seconds"), 2, TimeUnit.SECONDS);
// Called every 30 minutes
TaskKit.runInterval(() -> log.info("tick 30 Minute"), 30, TimeUnit.MINUTES);

example - TaskListener - Advanced Usage
//【Example - Remove Task】Called every second. Remove the current Listener when hp is 0.
TaskKit.runInterval(new IntervalTaskListener() {
    int hp = 2;

    @Override
    public void onUpdate() {
        hp--;
        log.info("Remaining hp:2-{}", hp);
    }

    @Override
    public boolean isActive() {
        // Returning false indicates inactive, and the current Listener will be removed from the listener list
        return hp != 0;
    }
}, 1, TimeUnit.SECONDS);

//【Example - Skip Execution】Called every second. The onUpdate method is executed only when triggerUpdate returns true (i.e., the condition is met).
TaskKit.runInterval(new IntervalTaskListener() {
    int hp;

    @Override
    public void onUpdate() {
        log.info("current hp:{}", hp);
    }

    @Override
    public boolean triggerUpdate() {
        hp++;
        // When the return value is true, the onUpdate method is executed
        return hp % 2 == 0;
    }
}, 1, TimeUnit.SECONDS);

//【Example - Specify Thread Executor】Called every second
// If there are time-consuming tasks, such as those involving I/O operations, it is recommended to specify an executor to run the current callback (onUpdate method) to avoid blocking other tasks.
TaskKit.runInterval(new IntervalTaskListener() {
    @Override
    public void onUpdate() {
        log.info("Executing time-consuming I/O task, start");

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        log.info("Executing time-consuming I/O task, end");
    }

    @Override
    public Executor getExecutor() {
        // Specify an executor to run the current callback (onUpdate method) to avoid blocking other tasks.
        return TaskKit.getCacheExecutor();
    }
}, 1, TimeUnit.SECONDS);

Author:
渔民小镇
date:
2023-12-02
  • Constructor Details

    • TaskKit

      public TaskKit()
  • Method Details

    • setTimer

      public void setTimer(io.netty.util.Timer timer)
      set HashedWheelTimer
      TaskKit.setTimer(new HashedWheelTimer(17, TimeUnit.MILLISECONDS));
      
      
      Parameters:
      timer - Timer
      Since:
      21.23
    • execute

      public void execute(Runnable command)
    • executeVirtual

      public void executeVirtual(Runnable command)
    • supplyAsync

      public <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
      Returns a CompletableFuture where the task runs asynchronously on the virtualExecutor (virtual thread), and the result is obtained from the Supplier.
      Type Parameters:
      U - u
      Parameters:
      supplier - supplier
      Returns:
      CompletableFuture
      See Also:
      • virtualExecutor
    • newTimeout

      public io.netty.util.Timeout newTimeout(io.netty.util.TimerTask task, long delay, TimeUnit unit)
      Executes the task after a certain delay;
      Parameters:
      task - task
      delay - delay time
      unit - delay time unit
      Returns:
      Timeout
    • runOnce

      public void runOnce(OnceTaskListener taskListener, long delay, TimeUnit unit)
      Add OnceTaskListener callback, will only be executed once.
      Parameters:
      taskListener - taskListener
      delay - delay time
      unit - delay time unit
    • runOnceSecond

      public void runOnceSecond(OnceTaskListener taskListener)
      Execute OnceTaskListener callback after one second, will only be executed once.
      Parameters:
      taskListener - taskListener
    • runOnceMillis

      public void runOnceMillis(OnceTaskListener taskListener, long delayMilliseconds)
      Add OnceTaskListener callback, will only be executed once.
      Parameters:
      taskListener - taskListener
      delayMilliseconds - delayMilliseconds
    • runIntervalMinute

      public void runIntervalMinute(IntervalTaskListener taskListener, long tickMinute)
      Add scheduled task listener
      Parameters:
      taskListener - scheduled task listener
      tickMinute - The listener will be called once every tickMinute minutes.
    • runInterval

      public void runInterval(IntervalTaskListener taskListener, long tick, TimeUnit timeUnit)
      Add task listener callback
      The task listener will be called once every tick time unit.
      
      Parameters:
      taskListener - task listener
      tick - tick time interval; the listener will be called once every tick time interval
      timeUnit - tick time unit
    • stop

      public void stop()