PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
TaskHandler.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\scheduler;
25
28
30 protected int $nextRun;
31
32 protected bool $cancelled = false;
33
34 private TimingsHandler $timings;
35
36 private string $taskName;
37 private string $ownerName;
38
39 public function __construct(
40 protected Task $task,
41 protected int $delay = -1,
42 protected int $period = -1,
43 ?string $ownerName = null
44 ){
45 if($task->getHandler() !== null){
46 throw new \InvalidArgumentException("Cannot assign multiple handlers to the same task");
47 }
48 $this->taskName = $task->getName();
49 $this->ownerName = $ownerName ?? "Unknown";
50 $this->timings = Timings::getScheduledTaskTimings($this, $period);
51 $this->task->setHandler($this);
52 }
53
54 public function isCancelled() : bool{
55 return $this->cancelled;
56 }
57
58 public function getNextRun() : int{
59 return $this->nextRun;
60 }
61
65 public function setNextRun(int $ticks) : void{
66 $this->nextRun = $ticks;
67 }
68
69 public function getTask() : Task{
70 return $this->task;
71 }
72
73 public function getDelay() : int{
74 return $this->delay;
75 }
76
77 public function isDelayed() : bool{
78 return $this->delay > 0;
79 }
80
81 public function isRepeating() : bool{
82 return $this->period > 0;
83 }
84
85 public function getPeriod() : int{
86 return $this->period;
87 }
88
89 public function cancel() : void{
90 try{
91 if(!$this->isCancelled()){
92 $this->task->onCancel();
93 }
94 }finally{
95 $this->remove();
96 }
97 }
98
102 public function remove() : void{
103 $this->cancelled = true;
104 $this->task->setHandler(null);
105 }
106
110 public function run() : void{
111 $this->timings->startTiming();
112 try{
113 $this->task->onRun();
114 }catch(CancelTaskException $e){
115 $this->cancel();
116 }finally{
117 $this->timings->stopTiming();
118 }
119 }
120
121 public function getTaskName() : string{
122 return $this->taskName;
123 }
124
125 public function getOwnerName() : string{
126 return $this->ownerName;
127 }
128}