下面列出了怎么用org.bukkit.scheduler.BukkitTask的API类实例代码及写法,或者点击链接到github查看源代码。
public void revertClaimVisual(GDClaim claim, UUID visualUniqueId) {
final Player player = this.getSubject().getOnlinePlayer();
if (player == null) {
return;
}
for (Map.Entry<UUID, BukkitTask> mapEntry : this.claimVisualRevertTasks.entrySet()) {
if (visualUniqueId.equals(mapEntry.getKey())) {
mapEntry.getValue().cancel();
break;
}
}
if (GriefDefenderPlugin.getInstance().getWorldEditProvider() != null) {
GriefDefenderPlugin.getInstance().getWorldEditProvider().revertClaimCUIVisual(visualUniqueId, this.playerID);
}
this.revertVisualBlocks(player, claim, visualUniqueId);
}
/**
* This will rotate the shape around in an area randomly.
* The position of the shape will be randomized positively and negatively by the offset parameters on each axis.
*
* @param plugin the schedule handler.
* @param update the timer period in ticks.
* @param rate the distance between each location. Recommended value is 5.
* @param runnable the particles to spawn.
* @param displays the displays references used to spawn particles in the runnable.
* @return the async task handling the movement.
* @see #moveRotatingAround(JavaPlugin, long, double, double, double, double, Runnable, ParticleDisplay...)
* @see #guard(JavaPlugin, long, double, double, double, double, Runnable, ParticleDisplay...)
* @since 1.0.0
*/
public static BukkitTask rotateAround(JavaPlugin plugin, long update, double rate, double offsetx, double offsety, double offsetz,
Runnable runnable, ParticleDisplay... displays) {
return new BukkitRunnable() {
double rotation = 180;
@Override
public void run() {
rotation += rate;
double x = Math.toRadians((90 + rotation) * offsetx);
double y = Math.toRadians((60 + rotation) * offsety);
double z = Math.toRadians((30 + rotation) * offsetz);
Vector vector = new Vector(x, y, z);
for (ParticleDisplay display : displays) display.rotate(vector);
runnable.run();
}
}.runTaskTimerAsynchronously(plugin, 0L, update);
}
/**
* Display a rendered image repeatedly.
*
* @param plugin the scheduler handler.
* @param render the rendered image map.
* @param location the dynamic location to display the image at.
* @param repeat amount of times to repeat displaying the image.
* @param period the perioud between each repeats.
* @param quality the quality of the image is exactly the number of particles display for each pixel. Recommended value is 1
* @param speed the speed is exactly the same value as the speed of particles. Recommended amount is 0
* @param size the size of the particle. Recommended amount is 0.8
* @return the async bukkit task displaying the image.
* @since 1.0.0
*/
public static BukkitTask displayRenderedImage(JavaPlugin plugin, Map<Location, Color> render, Callable<Location> location,
int repeat, long period, int quality, int speed, float size) {
return new BukkitRunnable() {
int times = repeat;
@Override
public void run() {
try {
displayRenderedImage(render, location.call(), quality, speed, size);
} catch (Exception e) {
e.printStackTrace();
}
if (times-- < 1) cancel();
}
}.runTaskTimerAsynchronously(plugin, 0L, period);
}
@Override
public Hologram createSimpleHologram(Location location, int secondsUntilRemoved, final Vector velocity, String... lines) {
int simpleId = TagIdGenerator.next(lines.length);
final Hologram hologram = new HologramFactory(HoloAPI.getCore()).withFirstTagId(simpleId).withSaveId(simpleId + "").withText(lines).withLocation(location).withSimplicity(true).build();
for (Entity e : hologram.getDefaultLocation().getWorld().getEntities()) {
if (e instanceof Player) {
hologram.show((Player) e, true);
}
}
BukkitTask t = HoloAPI.getCore().getServer().getScheduler().runTaskTimer(HoloAPI.getCore(), new Runnable() {
@Override
public void run() {
Location l = hologram.getDefaultLocation();
l.add(velocity);
hologram.move(l.toVector());
}
}, 1L, 1L);
new HologramRemoveTask(hologram, t).runTaskLater(HoloAPI.getCore(), secondsUntilRemoved * 20);
return hologram;
}
/**
* Teleport the given {@link Player} to the given {@link Location}, loading the {@link org.bukkit.Chunk} before
* teleporting and with the configured teleport delay if applicable.
* @param player Player to teleport.
* @param targetLocation Location to teleport the player to.
* @param force True to override teleport delay, false otherwise.
*/
public void safeTeleport(@NotNull Player player, @NotNull Location targetLocation, boolean force) {
Validate.notNull(player, "Player cannot be null");
Validate.notNull(targetLocation, "TargetLocation cannot be null");
log.log(Level.FINER, "safeTeleport " + player + " to " + targetLocation + (force ? " with force" : ""));
final Location targetLoc = LocationUtil.centerOnBlock(targetLocation.clone());
if (player.hasPermission("usb.mod.bypassteleport") || (teleportDelay == 0) || force) {
PaperLib.teleportAsync(player, targetLoc);
} else {
player.sendMessage(tr("\u00a7aYou will be teleported in {0} seconds.", teleportDelay));
BukkitTask tpTask = plugin.sync(() -> {
pendingTeleports.remove(player.getUniqueId());
PaperLib.teleportAsync(player, targetLoc);
}, TimeUtil.secondsAsMillis(teleportDelay));
pendingTeleports.put(player.getUniqueId(), new PendingTeleport(player.getLocation(), tpTask));
}
}
@Test
public void shouldCancelExistingTimeoutTask() {
// given
Player player = mock(Player.class);
LimboPlayer limboPlayer = new LimboPlayer(null, false, Collections.emptyList(), true, 0.3f, 0.1f);
BukkitTask existingTask = mock(BukkitTask.class);
limboPlayer.setTimeoutTask(existingTask);
given(settings.getProperty(RestrictionSettings.TIMEOUT)).willReturn(18);
BukkitTask bukkitTask = mock(BukkitTask.class);
given(bukkitService.runTaskLater(any(TimeoutTask.class), anyLong())).willReturn(bukkitTask);
// when
limboPlayerTaskManager.registerTimeoutTask(player, limboPlayer);
// then
verify(existingTask).cancel();
assertThat(limboPlayer.getTimeoutTask(), equalTo(bukkitTask));
verify(bukkitService).runTaskLater(any(TimeoutTask.class), eq(360L)); // 18 * TICKS_PER_SECOND
verify(messages).retrieveSingle(player, MessageKey.LOGIN_TIMEOUT_ERROR);
}
private BaseComponent[] formatTask(BukkitTask pendingTask) {
Plugin owner = pendingTask.getOwner();
int taskId = pendingTask.getTaskId();
boolean sync = pendingTask.isSync();
String id = Integer.toString(taskId);
if (sync) {
id += "-Sync";
} else if (Bukkit.getScheduler().isCurrentlyRunning(taskId)) {
id += "-Running";
}
return new ComponentBuilder(owner.getName())
.color(PRIMARY_COLOR.asBungee())
.append('-' + id)
.color(SECONDARY_COLOR.asBungee())
.create();
}
private BaseComponent[] formatTask(BukkitTask pendingTask) {
Plugin owner = pendingTask.getOwner();
int taskId = pendingTask.getTaskId();
boolean sync = pendingTask.isSync();
String id = Integer.toString(taskId);
if (sync) {
id += "-Sync";
} else if (Bukkit.getScheduler().isCurrentlyRunning(taskId)) {
id += "-Running";
}
return new ComponentBuilder(owner.getName())
.color(PRIMARY_COLOR.asBungee())
.append('-' + id)
.color(SECONDARY_COLOR.asBungee())
.create();
}
@Test
public void shouldStopTaskAndInformConsoleUser() {
// given
Set<String> names = newHashSet("name1", "name2");
PurgeTask task = new PurgeTask(purgeService, permissionsManager, null, names, new OfflinePlayer[0]);
BukkitTask bukkitTask = mock(BukkitTask.class);
given(bukkitTask.getTaskId()).willReturn(10049);
ReflectionTestUtils.setField(BukkitRunnable.class, task, "task", bukkitTask);
Server server = mock(Server.class);
BukkitScheduler scheduler = mock(BukkitScheduler.class);
given(server.getScheduler()).willReturn(scheduler);
ReflectionTestUtils.setField(Bukkit.class, null, "server", server);
ConsoleCommandSender consoleSender = mock(ConsoleCommandSender.class);
given(server.getConsoleSender()).willReturn(consoleSender);
task.run(); // Run for the first time -> results in empty names list
// when
task.run();
// then
verify(scheduler).cancelTask(task.getTaskId());
verify(consoleSender).sendMessage(argThat(containsString("Database has been purged successfully")));
}
@Override
public void revertAllVisuals() {
this.lastShovelLocation = null;
this.claimResizing = null;
this.claimSubdividing = null;
final Player player = this.getSubject().getOnlinePlayer();
if (player == null) {
return;
}
if (this.visualClaimBlocks.isEmpty()) {
return;
}
for (Map.Entry<UUID, BukkitTask> mapEntry : this.claimVisualRevertTasks.entrySet()) {
mapEntry.getValue().cancel();
}
final List<UUID> visualIds = new ArrayList<>(this.visualClaimBlocks.keySet());
for (UUID visualUniqueId : visualIds) {
final Claim claim = GriefDefenderPlugin.getInstance().dataStore.getClaim(player.getWorld().getUID(), visualUniqueId);
this.revertVisualBlocks(player, (GDClaim) claim, visualUniqueId);
}
if (GriefDefenderPlugin.getInstance().getWorldEditProvider() != null) {
GriefDefenderPlugin.getInstance().getWorldEditProvider().revertAllVisuals(this.playerID);
}
// Revert any temp visuals
this.revertTempVisuals();
}
/**
* Spawns connected 3D ellipses.
*
* @param plugin the timer handler.
* @param maxRadius the maximum radius for the ellipses.
* @param rate the rate of the 3D ellipses circle points.
* @param radiusRate the rate of the circle radius change.
* @param extend the extension for each ellipse.
* @return the animation handler.
* @see #magicCircles(JavaPlugin, double, double, double, double, ParticleDisplay)
* @since 3.0.0
*/
public static BukkitTask circularBeam(JavaPlugin plugin, double maxRadius, double rate, double radiusRate, double extend, ParticleDisplay display) {
return new BukkitRunnable() {
final double rateDiv = Math.PI / rate;
final double radiusDiv = Math.PI / radiusRate;
final Vector dir = display.location.getDirection().normalize().multiply(extend);
double dynamicRadius = 0;
@Override
public void run() {
// If we wanted to use actual numbers as the radius then the curve for
// each loop wouldn't be smooth.
double radius = maxRadius * Math.sin(dynamicRadius);
// Spawn normal circles.
for (double theta = 0; theta < PII; theta += rateDiv) {
double x = radius * Math.sin(theta);
double z = radius * Math.cos(theta);
display.spawn(x, 0, z);
}
dynamicRadius += radiusDiv;
if (dynamicRadius > Math.PI) dynamicRadius = 0;
// Next circle center location.
display.location.add(dir);
}
}.runTaskTimerAsynchronously(plugin, 0L, 1L);
}
private void updateLeaveMenuItemTimer(final Player p, final Inventory inventory, final ItemStack currentItem) {
final BukkitTask[] hackySharing = new BukkitTask[1];
hackySharing[0] = plugin.sync(() -> {
long millisLeft = plugin.getConfirmHandler().millisLeft(p, "/is leave");
if (inventory.getViewers().contains(p)) {
updateLeaveMenuItem(inventory, currentItem, millisLeft);
}
if (millisLeft <= 0 || !inventory.getViewers().contains(p)) {
if (hackySharing.length > 0 && hackySharing[0] != null) {
hackySharing[0].cancel();
}
}
}, 0, 1000);
}
public static boolean hasTask(String key) {
BukkitTask task = tasks.get(key);
if (task == null) {
return false;
}
if (BukkitObjects.getScheduler().isCurrentlyRunning(task.getTaskId()) || BukkitObjects.getScheduler().isQueued(task.getTaskId())) {
return true;
}
tasks.remove(key);
return false;
}
/**
* Set the timeout task of the player. The timeout task kicks the player after a configurable
* amount of time if he hasn't logged in or registered.
*
* @param timeoutTask The task to set
*/
public void setTimeoutTask(BukkitTask timeoutTask) {
if (this.timeoutTask != null) {
this.timeoutTask.cancel();
}
this.timeoutTask = timeoutTask;
}
@Override
public BukkitTask startTask(Task.Parameters schedule, Runnable runnable) {
final Duration delay = schedule.delay();
final Duration interval = schedule.interval();
return bukkit.runTaskTimer(plugin,
runnable,
delay == null ? 0 : TimeUtils.toTicks(delay),
interval == null ? -1 : TimeUtils.toTicks(interval));
}
@Override
public BukkitTask runTask(Plugin plugin, Runnable runnable) throws IllegalArgumentException {
TaskedRunnable wrapped = new TaskedRunnable(runnable);
BukkitTask bukkitTask = delegate.runTask(plugin, wrapped);
wrapped.setTaskID(bukkitTask.getTaskId());
return bukkitTask;
}
@Override
public BukkitTask runTask(Plugin plugin, BukkitRunnable bukkitRunnable)
throws IllegalArgumentException {
TaskedRunnable wrapped = new TaskedRunnable(bukkitRunnable);
BukkitTask bukkitTask = delegate.runTask(plugin, wrapped);
wrapped.setTaskID(bukkitTask.getTaskId());
return bukkitTask;
}
private Class<?> getRunnableClass(BukkitTask task) {
try {
return taskHandle.invokeExact(task).getClass();
} catch (Exception ex) {
//ignore
} catch (Throwable throwable) {
throw (Error) throwable;
}
return null;
}
@Override
public BukkitTask runTaskLater(Plugin plugin, BukkitRunnable bukkitRunnable, long l)
throws IllegalArgumentException {
TaskedRunnable wrapped = new TaskedRunnable(bukkitRunnable);
BukkitTask bukkitTask = delegate.runTaskLater(plugin, wrapped, l);
wrapped.setTaskID(bukkitTask.getTaskId());
return bukkitTask;
}
@Override
public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable runnable, long l)
throws IllegalArgumentException {
TaskedRunnable wrapped = new TaskedRunnable(runnable);
BukkitTask bukkitTask = delegate.runTaskLaterAsynchronously(plugin, wrapped, l);
wrapped.setTaskID(bukkitTask.getTaskId());
return bukkitTask;
}
@Override
public BukkitTask runTaskLaterAsynchronously(Plugin plugin, BukkitRunnable bukkitRunnable, long l)
throws IllegalArgumentException {
TaskedRunnable wrapped = new TaskedRunnable(bukkitRunnable);
BukkitTask bukkitTask = delegate.runTaskLaterAsynchronously(plugin, wrapped, l);
wrapped.setTaskID(bukkitTask.getTaskId());
return bukkitTask;
}
@Test
public void shouldRunTask() {
// given
Runnable task = () -> {/* noop */};
BukkitTask bukkitTask = mock(BukkitTask.class);
given(scheduler.runTask(authMe, task)).willReturn(bukkitTask);
// when
BukkitTask resultingTask = bukkitService.runTask(task);
// then
assertThat(resultingTask, equalTo(bukkitTask));
verify(scheduler, only()).runTask(authMe, task);
}
public static BukkitTask runSync(Runnable r) {
if (SlimefunPlugin.getMinecraftVersion() == MinecraftVersion.UNIT_TEST) {
r.run();
return null;
}
return Bukkit.getScheduler().runTask(SlimefunPlugin.instance, r);
}
public static void cancelTimer(String name) {
BukkitTask timer = tasks.get(name);
if (timer != null) {
timer.cancel();
}
//RJ.out("cancel timer:"+name);
timers.remove(name);
}
private BukkitTask createTask(String path, BukkitTask existing, Runnable runnable) {
if (existing != null) {
existing.cancel();
}
if (config.getInt(path, -1) <= 0) return null;
return Bukkit.getScheduler().runTaskTimer(plugin, runnable, 0, 20 * config.getInt(path));
}
/**
* Ends the tasks running by a player.
* @param player The player using the crate.
*/
public void endQuadCrate(Player player) {
if (currentQuadTasks.containsKey(player.getUniqueId())) {
for (BukkitTask task : currentQuadTasks.get(player.getUniqueId())) {
task.cancel();
}
currentQuadTasks.remove(player.getUniqueId());
}
}
public static void stopAllTimers() {
for (BukkitTask timer : timers.values()) {
timer.cancel();
}
//RJ.out("clearing timers");
timers.clear();
}
private void loadConfig() {
particlesTasks.forEach(BukkitTask::cancel);
particlesTasks.clear();
for (SelectionType type : SelectionType.values()) {
GlobalSelectionConfig config = configurationHelper.loadGlobalSelectionConfig(type);
configurations.put(type, config);
particlesTasks.add(new ParticlesTask(this, type, true, config.primary()).start());
particlesTasks.add(new ParticlesTask(this, type, false, config.secondary()).start());
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!canExecute(sender, command)) {
return true;
}
List<BaseComponent[]> lines = new ArrayList<>();
List<BukkitTask> pendingTasks = Bukkit.getScheduler().getPendingTasks();
for (BukkitTask pendingTask : pendingTasks) {
lines.add(formatTask(pendingTask));
Class<?> runnableClass = getRunnableClass(pendingTask);
if (runnableClass != null) {
lines.add(new ComponentBuilder(" Task: ")
.color(PRIMARY_COLOR.asBungee())
.append(runnableClass.getSimpleName())
.color(SECONDARY_COLOR.asBungee())
.create());
}
}
Pages pagination = new Pages("Stacktrace", lines);
pagination.send(sender);
plugin.getPageManager().setPagination(sender.getName(), pagination);
return true;
}
public void stopWorkers() {
for (BukkitTask task : this.runningTasks) {
try {
task.cancel();
} catch (Exception ex) {
BedwarsRel.getInstance().getBugsnag().notify(ex);
// already cancelled
}
}
this.runningTasks.clear();
}