1. The forums will be archived and moved to a read only mode in about 2 weeks (mid march).

How to use Closure Task

Discussion in 'Plugin Help' started by PJZ9n, Jun 17, 2020.

  1. PJZ9n

    PJZ9n Silverfish

    Messages:
    17
    GitHub:
    pjz9n
    Hi, I thought I'd use ClosureTask but when I try to stop RepeatingTask I still can't get the TaskHandler inside Closure. What should I do with this?
     
  2. Heisenburger69

    Heisenburger69 Silverfish

    Messages:
    16
    GitHub:
    heisenburger69
    PHP:
    $task = new ClosureTask(...);
    $this->getScheduler()->scheduleRepeatingTask($task20);
    $handler $task->getHandler();
    // Do whatever you want to do with the handler, f.e: Cancelling the event
    where $this is an instance of PluginBase
     
  3. PJZ9n

    PJZ9n Silverfish

    Messages:
    17
    GitHub:
    pjz9n
    PHP:
            $task = new ClosureTask(function (int $currentTick): void {
                if (
    mt_rand(0100) === 0) {
                    
    //end the task...
                    //what TaskHandler...
                    
    $this->handler->cancel();
                    return;
                }
                
    $this->getServer()->getLogger()->info("Hello!");
            });
            
    $this->handler $this->getScheduler()->scheduleRepeatingTask($task20);
    Is there a smart way to cancel a task from within a closure like this?
    Otherwise, you have to store Task in the property of the main class.
    I don't know if this is smart.
     
  4. Heisenburger69

    Heisenburger69 Silverfish

    Messages:
    16
    GitHub:
    heisenburger69
    Don't think you can do that, no
     
  5. wolfdale

    wolfdale Zombie Pigman

    Messages:
    535
    GitHub:
    diamond-gold
    You can simply do this
    PHP:
    $handler $this->getScheduler()->scheduleRepeatingTask(new ClosureTask(function (int $currentTick)use(&$handler): void {
                if (
    mt_rand(0100) === 0) {
                    
    //end the task...
                    
    $handler->cancel();
                    return;
                }
                
    $this->getServer()->getLogger()->info("Hello!");
            }), 
    20);
     
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.