Plex/src/main/java/dev/plex/services/ServiceManager.java

100 lines
2.7 KiB
Java
Raw Normal View History

2021-01-03 07:21:15 +00:00
package dev.plex.services;
import com.google.common.collect.Lists;
2021-01-03 07:21:15 +00:00
import dev.plex.Plex;
import dev.plex.services.impl.*;
2022-01-27 21:23:01 +00:00
import org.bukkit.Bukkit;
2022-04-07 00:38:15 +00:00
import org.bukkit.scheduler.BukkitTask;
import java.util.List;
public class ServiceManager
{
private final List<AbstractService> services = Lists.newArrayList();
public ServiceManager()
{
2022-03-03 21:43:28 +00:00
registerService(new BanService());
2022-01-27 06:36:00 +00:00
registerService(new GameRuleService());
2022-03-03 23:24:15 +00:00
registerService(new UpdateCheckerService());
registerService(new AutoWipeService());
2022-04-08 21:57:09 +00:00
registerService(new CommandBlockerService());
}
public void startServices()
{
for (AbstractService service : services)
{
2022-04-07 02:05:29 +00:00
startService(service);
}
}
2022-04-07 02:05:29 +00:00
public void endServices()
{
services.forEach(this::endService);
}
2022-04-07 00:38:15 +00:00
public AbstractService getService(Class<? extends AbstractService> clazz)
{
return services.stream().filter(service -> service.getClass().isAssignableFrom(clazz)).findFirst().orElse(null);
}
public void startService(AbstractService service)
{
if (!service.isRepeating())
{
2022-04-08 06:15:25 +00:00
int time = service.repeatInSeconds();
BukkitTask task;
if (time == 0)
{
task = Bukkit.getScheduler().runTask(Plex.get(), service::run);
}
else
{
task = Bukkit.getScheduler().runTaskLater(Plex.get(), service::run, time);
}
2022-04-07 00:38:15 +00:00
service.setTaskId(task.getTaskId());
2022-04-07 04:49:45 +00:00
}
else if (service.isRepeating() && service.isAsynchronous())
2022-04-07 00:38:15 +00:00
{
BukkitTask task = Bukkit.getScheduler().runTaskTimerAsynchronously(Plex.get(), service::run, 0, 20L * service.repeatInSeconds());
service.setTaskId(task.getTaskId());
2022-04-07 04:49:45 +00:00
}
else if (service.isRepeating() && !service.isAsynchronous())
2022-04-07 00:38:15 +00:00
{
BukkitTask task = Bukkit.getScheduler().runTaskTimer(Plex.get(), service::run, 0, 20L * service.repeatInSeconds());
service.setTaskId(task.getTaskId());
}
2022-04-07 02:05:29 +00:00
if (!services.contains(service))
{
services.add(service);
}
service.onStart();
2022-04-07 00:38:15 +00:00
}
2022-04-07 02:05:29 +00:00
public void endService(AbstractService service, boolean remove)
2022-04-07 00:38:15 +00:00
{
Bukkit.getScheduler().cancelTask(service.getTaskId());
2022-04-07 02:05:29 +00:00
service.onEnd();
if (remove)
{
services.remove(service);
}
}
public void endService(AbstractService service)
{
endService(service, false);
}
private void registerService(AbstractService service)
{
services.add(service);
}
public int serviceCount()
{
return services.size();
}
}