Exemple #1
0
        static void Beat(SchedulerTask scheduledTask)
        {
            if (Server.IsShuttingDown) return;

            if (ConfigKey.HeartbeatEnabled.Enabled())
            {
                SendMinecraftNetBeat();
                if (ConfigKey.IsPublic.Enabled() && ConfigKey.HeartbeatToWoMDirect.Enabled())
                {
                    SendWoMDirectBeat();
                }

            }
            else
            {
                string[] data = new[]{
                    Salt,
                    Server.InternalIP.ToString(),
                    Server.Port.ToString(),
                    Server.CountPlayers( false ).ToString(),
                    ConfigKey.MaxPlayers.GetString(),
                    ConfigKey.ServerName.GetString(),
                    ConfigKey.IsPublic.GetString()
                };
                const string tempFile = Paths.HeartbeatDataFileName + ".tmp";
                File.WriteAllLines(tempFile, data, Encoding.ASCII);
                Paths.MoveOrReplace(tempFile, Paths.HeartbeatDataFileName);
            }
        }
Exemple #2
0
        public static void CheckGrass(SchedulerTask task)
        {
            if (checkGrass != null)
            {
                if (checkGrass.ThreadState != ThreadState.Stopped)
                {
                    return;
                }
            }

            checkGrass = new Thread(new ThreadStart(delegate
            {
                foreach (World world in WorldManager.Worlds)
                {
                    if (world.Map != null && world.IsLoaded)
                    {
                        for (int x = world.Map.Bounds.XMin; x < world.Map.Bounds.XMax; x++)
                        {
                            if (world.Map == null)
                            {
                                break;
                            }

                            for (int y = world.Map.Bounds.YMin; y < world.Map.Bounds.YMax; y++)
                            {
                                if (world.Map == null)
                                {
                                    break;
                                }

                                for (int z = world.Map.Bounds.ZMin; z < world.Map.Bounds.ZMax; z++)
                                {
                                    if (world.Map == null)
                                    {
                                        break;
                                    }

                                    if (world.Map.GetBlock(new Vector3I(x, y, z)) == Block.Dirt)
                                    {
                                        if (CanPutGrassOn(new Vector3I(x, y, z), world))
                                        {
                                            // Okay let's plant some seeds
                                            int randomDelay = new Random().Next(1, 60001);
                                            GrassUpdate update = new GrassUpdate(world, new Vector3I(x, y, z), DateTime.Now.AddMilliseconds(randomDelay));

                                            lock (grassQueue.SyncRoot)
                                            {
                                                grassQueue.Add(update);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }));
            checkGrass.Start();
        }
        public ScriptFlow(SchedulerTask goal)
        {
            this.goal = goal;

            IsGoalFinished = false;
            ScheduledScripts = new List<KeyValuePair<string, long>>();
            ScheduledScriptsNext = new List<KeyValuePair<string, long>>();
            messages = new List<ScriptAssertionMessage>();
        }
Exemple #4
0
 public static void CheckAutoRankSetting() {
     if( ConfigKey.AutoRankEnabled.GetBool() ) {
         if( task == null ) {
             task = Scheduler.NewBackgroundTask( TaskCallback );
             task.RunForever( TickInterval );
         } else if( task.IsStopped ) {
             task.RunForever( TickInterval );
         }
     } else if( task != null && !task.IsStopped ) {
         task.Stop();
     }
 }
Exemple #5
0
        private static void doorTimer_Elapsed(SchedulerTask task)
        {
            DoorInfo info    = (DoorInfo)task.UserState;
            int      counter = 0;

            for (int x = info.Door.Range.Xmin; x <= info.Door.Range.Xmax; x++)
            {
                for (int y = info.Door.Range.Ymin; y <= info.Door.Range.Ymax; y++)
                {
                    for (int z = info.Door.Range.Zmin; z <= info.Door.Range.Zmax; z++)
                    {
                        info.WorldMap.QueueUpdate(new BlockUpdate(null, new Vector3I(x, y, z), info.Buffer[counter]));
                        counter++;
                    }
                }
            }

            lock (openDoorsLock)
            {
                openDoors.Remove(info.Door);
            }
        }
Exemple #6
0
        public override void Use(Player p, string message)
        {
            if (!Hacks.CanUseHacks(p, p.level))
            {
                Player.Message(p, "You cannot use %T/Fly %Son this map.");
                p.isFlying = false; return;
            }

            p.isFlying = !p.isFlying;
            if (!p.isFlying)
            {
                return;
            }

            Player.Message(p, "You are now flying. &cJump!");

            FlyState state = new FlyState();

            state.player = p;
            SchedulerTask task = new SchedulerTask(FlyCallback, state, TimeSpan.Zero, true);

            p.CriticalTasks.Add(task);
        }
Exemple #7
0
        public override void Use(Player p, string message, CommandData data)
        {
            if (!Hacks.CanUseFly(p))
            {
                p.Message("You cannot use &T/Fly &Son this map.");
                p.isFlying = false; return;
            }

            p.isFlying = !p.isFlying;
            if (!p.isFlying)
            {
                return;
            }

            p.Message("You are now flying. &cJump!");

            FlyState state = new FlyState();

            state.player = p;
            SchedulerTask task = new SchedulerTask(FlyCallback, state, TimeSpan.Zero, true);

            p.CriticalTasks.Add(task);
        }
        public virtual SchedulerTaskViewModel Create(SchedulerTaskViewModel task)
        {
            var schedulerTask = new SchedulerTask()
            {
                Title = task.Title,
                Start = task.Start,
                End = task.End,
                StartTimezone = task.StartTimezone,
                EndTimezone = task.EndTimezone,
                Description = task.Description,
                IsAllDay = task.IsAllDay,
                RecurrenceRule = task.RecurrenceRule,
                RecurrenceException = task.RecurrenceException,
                RecurrenceId = task.RecurrenceId,
                UserId = task.UserId,
                IsFinished = task.IsFinished
            };

            this.Data.SchedulerTasks.Add(schedulerTask);
            this.Data.SaveChanges();

            return task;
        }
        private static void DoorTimerElapsed(SchedulerTask task)
        {
            DoorInfo info = (DoorInfo)task.UserState;

            int counter = 0;

            for (int x = info.Zone.Bounds.XMin; x <= info.Zone.Bounds.XMax; x++)
            {
                for (int y = info.Zone.Bounds.YMin; y <= info.Zone.Bounds.YMax; y++)
                {
                    for (int z = info.Zone.Bounds.ZMin; z <= info.Zone.Bounds.ZMax; z++)
                    {
                        info.WorldMap.QueueUpdate(new BlockUpdate(null, new Vector3I(x, y, z), info.Buffer[counter]));

                        counter++;
                    }
                }
            }

            lock (OpenDoorsLock) {
                OpenDoors.Remove(info.Zone);
            }
        }
Exemple #10
0
        void Loop()
        {
            while (true)
            {
                SchedulerTask task = null;
                lock (tasks) {
                    if (tasks.Count > 0)
                    {
                        task = tasks.Dequeue();
                    }
                }

                if (task == null)
                {
                    handle.WaitOne();
                }
                else
                {
                    task.Execute();
                }
                Thread.Sleep(10);
            }
        }
Exemple #11
0
        ChatTimer(TimeSpan duration, [CanBeNull] string message, [NotNull] string startedBy)
        {
            if (startedBy == null)
            {
                throw new ArgumentNullException("startedBy");
            }
            StartedBy = startedBy;
            Message   = message;
            StartTime = DateTime.UtcNow;
            EndTime   = StartTime.Add(duration);
            Duration  = duration;
            int oneSecondRepeats = (int)duration.TotalSeconds + 1;

            if (duration > Hour)
            {
                announceIntervalIndex = AnnounceIntervals.Length - 1;
                lastHourAnnounced     = (int)duration.TotalHours;
            }
            else
            {
                for (int i = 0; i < AnnounceIntervals.Length; i++)
                {
                    if (duration <= AnnounceIntervals[i])
                    {
                        announceIntervalIndex = i - 1;
                        break;
                    }
                }
            }
            task = Scheduler.NewTask(TimerCallback, this);
            Id   = Interlocked.Increment(ref timerCounter);
            AddTimerToList(this);
            IsRunning = true;
            task.RunRepeating(TimeSpan.Zero,
                              TimeSpan.FromSeconds(1),
                              oneSecondRepeats);
        }
Exemple #12
0
        private void ConvertStateFromFollwerTo(RaftState newState)
        {
            switch (newState)
            {
            case RaftState.Follower:
                logger.Info($"RaftState {Name}: Follower->Follower");
                return;

            case RaftState.Candidate:
                logger.Info($"RaftState {Name}: Follower->Candidate");
                State = RaftState.Candidate;
                LeaderLostTimerTask?.Cancel();
                LeaderLostTimerTask = null;
                LogSequence.SetVoteFor(string.Empty);     // 先清除,在真正自荐前可以给别人投票。
                StartRequestVote();
                return;

            case RaftState.Leader:
                // 并发的RequestVote的结果如果没有判断当前状态,可能会到达这里。
                // 不是什么大问题。see ProcessRequestVoteResult
                logger.Info($"RaftState {Name} Impossible! Follower->Leader");
                return;
            }
        }
Exemple #13
0
        internal static void CleanupTask(SchedulerTask task)
        {
            lock (ipsLock) {
                if (!Server.Config.IPSpamCheck)
                {
                    ips.Clear(); return;
                }

                // Find all connections which last joined before the connection spam check interval
                DateTime      threshold = DateTime.UtcNow.Add(-Server.Config.IPSpamInterval);
                List <string> expired   = null;
                foreach (var kvp in ips)
                {
                    DateTime lastJoin = kvp.Value[kvp.Value.Count - 1];
                    if (lastJoin >= threshold)
                    {
                        continue;
                    }

                    if (expired == null)
                    {
                        expired = new List <string>();
                    }
                    expired.Add(kvp.Key);
                }

                if (expired == null)
                {
                    return;
                }
                foreach (string ip in expired)
                {
                    ips.Remove(ip);
                }
            }
        }
        /// <summary>
        /// Pass scheduler task with id <param name="taskId">task id to scheduler queue</param>
        /// </summary>
        public BaseResponse ExecuteTask(string taskId)
        {
            SchedulerTask schedulerTask = Uow.SchedulerTasks.GetById(taskId, SchedulerDestination);

            if (schedulerTask != null)
            {
                SchedulerQueue schedulerQueue = new SchedulerQueue
                {
                    TaskType     = schedulerTask.Type,
                    LockerMask   = 0,                  //schedulerTask.LockerMask,
                    Dependencies = schedulerTask.Dependencies,
                    Status       = SchedulerExecutionStatus.Pending,
                    PlannedDate  = DateTime.UtcNow.AddMinutes(-1),
                };

                CreateQueueTask(schedulerQueue, true);
            }
            else
            {
                return(ErrorCode.SchedulerTaskNotFound);
            }

            return(BaseResponse.Success());
        }
Exemple #15
0
        static void DoGC(SchedulerTask task)
        {
            if (!gcRequested) return;
            gcRequested = false;

            Process proc = Process.GetCurrentProcess();
            proc.Refresh();
            long usageBefore = proc.PrivateMemorySize64 / (1024 * 1024);

            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

            proc.Refresh();
            long usageAfter = proc.PrivateMemorySize64 / (1024 * 1024);

            Logger.Log(LogType.Debug,
                        "Server.DoGC: Collected on schedule ({0}->{1} MB).",
                        usageBefore, usageAfter);
        }
Exemple #16
0
        public static void Interval(SchedulerTask task)
        {
            //check to stop Interval
            if (world_ == null)
            {
                task.Stop();
                return;
            }
            if (world_.gameMode != GameMode.Infection)
            {
                world_ = null;
                task.Stop();
                return;
            }

            if (!isOn)
            {
                if (startTime != null && (DateTime.Now - startTime).TotalSeconds > timeDelay)
                {
                    foreach (Player p in world_.Players)
                    {
                        int x = rand.Next(2, world_.Map.Width);
                        int y = rand.Next(2, world_.Map.Length);
                        int z1 = 0;
                        for (int z = world_.Map.Height - 1; z > 0; z--)
                        {
                            if (world_.Map.GetBlock(x, y, z) != Block.Air)
                            {
                                z1 = z + 3;
                                break;
                            }
                        }

                        p.TeleportTo(new Position(x, y, z1 + 2).ToVector3I().ToPlayerCoords()); //teleport players to a random position
                        beginGame(p);

                        Player.Moving += PlayerMoved;
                        Player.JoinedWorld += PlayerLeftWorld;
                        Player.Disconnected += PlayerLeftServer;

                        chooseInfected();

                    }
                    isOn = true;
                    lastChecked = DateTime.Now;     //used for intervals
                    return;
                }
            }
            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.Now -  startTime).TotalSeconds));

            if (isOn) //Check for win conditions
            {
                if (world_.Players.Count(player => player.Info.isInfected) == world_.Players.Count())
                {
                    world_.Players.Message("");
                    world_.Players.Message("&cThe Zombies have won! All humans have died off!");
                    Player.Moving -= PlayerMoved;
                    Player.JoinedWorld -= PlayerLeftWorld;
                    Player.Disconnected -= PlayerLeftServer;
                    RevertGame();
                    return;
                }
                if (world_.Players.Count(player => player.Info.isInfected) == 0 && world_.Players.Count() > 0)
                {
                    world_.Players.Message("");
                    world_.Players.Message("&aThe Zombies have died off! The Humans win!");
                    Player.Moving -= PlayerMoved;
                    Player.JoinedWorld -= PlayerLeftWorld;
                    Player.Disconnected -= PlayerLeftServer;
                    RevertGame();
                    return;
                }
                if (timeLeft == 0)
                {
                    world_.Players.Message("");
                    world_.Players.Message("&aThe Zombies failed to infect everyone! The Humans win!");
                    Player.Moving -= PlayerMoved;
                    Player.JoinedWorld -= PlayerLeftWorld;
                    Player.Disconnected -= PlayerLeftServer;
                    RevertGame();
                    return;
                }

            }

            if (lastChecked != null && (DateTime.Now - lastChecked).TotalSeconds > 29.9 && timeLeft < timeLimit)
            {
                world_.Players.Message("&sThere are currently {0} human(s) and {1} zombie(s) left on {2}.", world_.Players.Count() - world_.Players.Count(player => player.Info.isInfected), world_.Players.Count(player => player.Info.isInfected), world_.ClassyName);
                world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
                lastChecked = DateTime.Now;
            }
        }
        public static async Task UnscheduleTask(this IScheduler scheduler, SchedulerTask task)
        {
            JobKey jobKey = new JobKey(task.Id.ToString(), ConstantsStorage.TASK_GROUP);

            await scheduler.DeleteJob(jobKey);
        }
Exemple #18
0
        public static void Interval(SchedulerTask task)
        {
            //check to stop Interval
            if (world_ == null)
            {
                task.Stop();
                return;
            }
            if (world_.gameMode != GameMode.Infection)
            {
                world_ = null;
                task.Stop();
                return;
            }

            if (!isOn)
            {
                if (startTime != null && (DateTime.Now - startTime).TotalSeconds > timeDelay)
                {
                    foreach (Player p in world_.Players)
                    {
                        int x  = rand.Next(2, world_.Map.Width);
                        int y  = rand.Next(2, world_.Map.Length);
                        int z1 = 0;
                        for (int z = world_.Map.Height - 1; z > 0; z--)
                        {
                            if (world_.Map.GetBlock(x, y, z) != Block.Air)
                            {
                                z1 = z + 3;
                                break;
                            }
                        }

                        p.TeleportTo(new Position(x, y, z1 + 2).ToVector3I().ToPlayerCoords()); //teleport players to a random position
                        BeginGame(p);

                        Player.Moving       += PlayerMoved;
                        Player.JoinedWorld  += PlayerLeftWorld;
                        Player.Disconnected += PlayerLeftServer;

                        ChooseInfected();
                    }
                    isOn        = true;
                    lastChecked = DateTime.Now;     //used for intervals
                    return;
                }
            }
            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.Now - startTime).TotalSeconds));

            if (isOn) //Check for win conditions
            {
                if (world_.Players.Count(player => player.Info.isInfected) == world_.Players.Count())
                {
                    world_.Players.Message("", 0);
                    world_.Players.Message("&cThe Zombies have won! All humans have died off!", 0);
                    Player.Moving       -= PlayerMoved;
                    Player.JoinedWorld  -= PlayerLeftWorld;
                    Player.Disconnected -= PlayerLeftServer;
                    RevertGame();
                    return;
                }
                if (world_.Players.Count(player => player.Info.isInfected) == 0 && world_.Players.Any())
                {
                    world_.Players.Message("", 0);
                    world_.Players.Message("&aThe Zombies have died off! The Humans win!", 0);
                    Player.Moving       -= PlayerMoved;
                    Player.JoinedWorld  -= PlayerLeftWorld;
                    Player.Disconnected -= PlayerLeftServer;
                    RevertGame();
                    return;
                }
                if (timeLeft == 0)
                {
                    world_.Players.Message("", 0);
                    world_.Players.Message("&aThe Zombies failed to infect everyone! The Humans win!", 0);
                    Player.Moving       -= PlayerMoved;
                    Player.JoinedWorld  -= PlayerLeftWorld;
                    Player.Disconnected -= PlayerLeftServer;
                    RevertGame();
                    return;
                }
            }

            if (lastChecked != null && (DateTime.Now - lastChecked).TotalSeconds > 29.9 && timeLeft < timeLimit)
            {
                world_.Players.Message("&sThere are currently {0} human(s) and {1} zombie(s) left on {2}.", 0, world_.Players.Count() - world_.Players.Count(player => player.Info.isInfected), world_.Players.Count(player => player.Info.isInfected), world_.ClassyName);
                world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", 0, timeLeft);
                lastChecked = DateTime.Now;
            }
        }
Exemple #19
0
 internal static void TaskCallback( SchedulerTask schedulerTask )
 {
     if( !ConfigKey.AutoRankEnabled.Enabled() ) return;
     PlayerInfo[] onlinePlayers = Server.Players.Select( p => p.Info ).ToArray();
     MaintenanceCommands.DoAutoRankAll( Player.AutoRank, onlinePlayers, false, "~AutoRank" );
 }
Exemple #20
0
 public static void TaskCallback( SchedulerTask schedulerTask ) {
     MaintenanceCommands.DoAutoRankAll( Player.Console, PlayerDB.GetPlayerListCopy(), false, "~AutoRank" );
 }
Exemple #21
0
        public static bool StartServer()
        {
            if (IsRunning)
            {
                throw new InvalidOperationException("Server is already running");
            }
            if (!libraryInitialized || !serverInitialized)
            {
                throw new InvalidOperationException("Server.InitLibrary and Server.InitServer must be called before Server.StartServer");
            }

            StartTime = DateTime.UtcNow;
            cpuUsageStartingOffset = Process.GetCurrentProcess().TotalProcessorTime;
            Players = new Player[0];

            RaiseEvent(Starting);

            if (ConfigKey.BackupDataOnStartup.Enabled())
            {
                BackupData();
            }

            Player.Console = new Player(ConfigKey.ConsoleName.GetString());
            Player.AutoRank = new Player("(AutoRank)");

            if (ConfigKey.BlockDBEnabled.Enabled()) BlockDB.Init();

            if (!WorldManager.LoadWorldList()) return false;
            WorldManager.SaveWorldList();

            Port = ConfigKey.Port.GetInt();
            InternalIP = IPAddress.Parse(ConfigKey.IP.GetString());

            try
            {
                listener = new TcpListener(InternalIP, Port);
                listener.Start();

            }
            catch (Exception ex)
            {
                Logger.Log(LogType.Error,
                            "Could not start listening on port {0}, stopping. ({1})",
                            Port, ex.Message);
                if (!ConfigKey.IP.IsBlank())
                {
                    Logger.Log(LogType.Warning,
                                "Do not use the \"Designated IP\" setting unless you have multiple NICs or IPs.");
                }
                return false;
            }

            InternalIP = ((IPEndPoint)listener.LocalEndpoint).Address;
            ExternalIP = CheckExternalIP();

            if (ExternalIP == null)
            {
                Logger.Log(LogType.SystemActivity,
                            "Server.Run: now accepting connections on port {0}", Port);
            }
            else
            {
                Logger.Log(LogType.SystemActivity,
                            "Server.Run: now accepting connections at {0}:{1}",
                            ExternalIP, Port);
            }

            WorldManager.UpdateWorldList();
            Logger.Log(LogType.SystemActivity,
                        "All available worlds: {0}",
                        WorldManager.Worlds.JoinToString(", ", w => w.Name));

            Logger.Log(LogType.SystemActivity,
                        "Main world: {0}; default rank: {1}",
                        WorldManager.MainWorld.Name, RankManager.DefaultRank.Name);

            checkConnectionsTask = Scheduler.NewTask(CheckConnections).RunForever(CheckConnectionsInterval);

            checkIdlesTask = Scheduler.NewTask(CheckIdles).RunForever(CheckIdlesInterval);

            try
            {
                MonitorProcessorUsage(null);
                Scheduler.NewTask(MonitorProcessorUsage).RunForever(MonitorProcessorUsageInterval,
                                                                       MonitorProcessorUsageInterval);
            }
            catch (Exception ex)
            {
                Logger.Log(LogType.Error,
                            "Server.StartServer: Could not start monitoring CPU use: {0}", ex);
            }

            PlayerDB.StartSaveTask();

            if (ConfigKey.AnnouncementInterval.GetInt() > 0)
            {
                TimeSpan announcementInterval = TimeSpan.FromMinutes(ConfigKey.AnnouncementInterval.GetInt());
                Scheduler.NewTask(ShowRandomAnnouncement).RunForever(announcementInterval);
            }

            gcTask = Scheduler.NewTask(DoGC).RunForever(GCInterval, TimeSpan.FromSeconds(45));

            Heartbeat.Start();
            if (ConfigKey.HeartbeatToWoMDirect.Enabled())
            {
                if (ExternalIP == null)
                {
                    Logger.Log(LogType.SystemActivity,
                                "WoM Direct heartbeat is enabled. To edit your server's appearence on the server list, " +
                                "see https://direct.worldofminecraft.com/server.php?port={0}&salt={1}",
                                Port, Heartbeat.Salt);
                }
                else
                {
                    Logger.Log(LogType.SystemActivity,
                                "WoM Direct heartbeat is enabled. To edit your server's appearence on the server list, " +
                                "see https://direct.worldofminecraft.com/server.php?ip={0}&port={1}&salt={2}",
                                ExternalIP, Port, Heartbeat.Salt);
                }
            }

            if (ConfigKey.RestartInterval.GetInt() > 0)
            {
                TimeSpan restartIn = TimeSpan.FromSeconds(ConfigKey.RestartInterval.GetInt());
                Shutdown(new ShutdownParams(ShutdownReason.Restarting, restartIn, true, true), false);
                ChatTimer.Start(restartIn, "Automatic Server Restart", Player.Console.Name);
            }

            if (ConfigKey.IRCBotEnabled.Enabled()) IRC.Start();

            Scheduler.NewTask(AutoRankManager.TaskCallback).RunForever(AutoRankManager.TickInterval);

            Scheduler.Start();
            IsRunning = true;

            RaiseEvent(Started);
            return true;
        }
Exemple #22
0
        private void ConvertStateFromCandidateTo(RaftState newState)
        {
            switch (newState)
            {
            case RaftState.Follower:
                logger.Info($"RaftState {Name}: Candidate->Follower");
                State = RaftState.Follower;
                VoteSuccess.Clear();     // 选举结束清除。

                LogSequence.SetVoteFor(string.Empty);
                StartRequestVoteDelayTask?.Cancel();
                StartRequestVoteDelayTask = null;
                WaitMajorityVoteTimoutTask?.Cancel();
                WaitMajorityVoteTimoutTask = null;
                StartLeaderLostTimerTask();
                return;

            case RaftState.Candidate:
                logger.Info($"RaftState {Name}: Candidate->Candidate");
                LogSequence.SetVoteFor(string.Empty);     // 先清除,在真正自荐前可以给别人投票。
                StartRequestVote();
                return;

            case RaftState.Leader:
                StartRequestVoteDelayTask?.Cancel();
                StartRequestVoteDelayTask = null;
                WaitMajorityVoteTimoutTask?.Cancel();
                WaitMajorityVoteTimoutTask = null;
                VoteSuccess.Clear();     // 选举结束清除。

                logger.Info($"RaftState {Name}: Candidate->Leader");
                State = RaftState.Leader;
                LogSequence.SetVoteFor(string.Empty);
                LeaderId = Name;     // set to self

                // (Reinitialized after election)
                var nextIndex = LogSequence.LastIndex + 1;
                Server.Config.ForEachConnector(
                    (c) =>
                {
                    var cex        = c as Server.ConnectorEx;
                    cex.NextIndex  = nextIndex;
                    cex.MatchIndex = 0;
                });

                // Upon election:
                // send initial empty AppendEntries RPCs
                // (heartbeat)to each server; repeat during
                // idle periods to prevent election timeouts(§5.2)
                LogSequence.AppendLog(new HeartbeatLog(HeartbeatLog.SetLeaderReadyEvent), false);
                HearbeatTimerTask = Scheduler.Instance.Schedule(
                    (ThisTask) =>
                {
                    var elapse = Util.Time.NowUnixMillis - LogSequence.AppendLogActiveTime;
                    if (elapse < RaftConfig.LeaderHeartbeatTimer)
                    {
                        LogSequence.AppendLog(new HeartbeatLog(), false);
                    }
                },
                    1000,
                    1000);
                return;
            }
        }
        /// <summary>
        /// 从生产任务中同步数据至项目进度
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="renew"></param>
        /// <returns></returns>
        public virtual async Task SyncProcessSchedule(int projectId, bool renew = false)
        {
            var project = await GetByIdFromCacheAsync(projectId);

            var schedulerTaskManager = Resolve <SchedulerTaskManager>();
            var partManager          = Resolve <PartManager>();

            using (CurrentUnitOfWork.SetTenantId(project.TenantId))
            {
                if (renew)
                {
                    //删除原有生产进度
                    await schedulerTaskManager.Repository.HardDeleteAsync(o => o.ProjectId == projectId && o.RelGroup == "Process");

                    await CurrentUnitOfWork.SaveChangesAsync();
                }
                //获取项目下的所有生产零件
                var parts = await partManager.GetAll()
                            .Where(o => o.ProjectId == projectId)
                            .Where(o => o.EnableProcess)
                            .OrderBy(o => o.Sort)
                            .Include("ProcessTasks.ProcessType")
                            .ToListAsync();

                //项目下的所有任务
                var oriTasks = await schedulerTaskManager.GetProjectSchedulerTasks(projectId);

                //1.生成生产进度节点
                var processWrapperTask = oriTasks
                                         .Where(o => o.ParentId == "0")
                                         .Where(o => o.RelGroup == "Process")
                                         .Where(o => o.TaskName == "生产进度")
                                         .FirstOrDefault();
                if (processWrapperTask == null)
                {
                    processWrapperTask = new SchedulerTask()
                    {
                        ProjectId      = projectId,
                        TaskName       = "生产进度",
                        TaskType       = "project",
                        PlanStartDate  = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")),
                        PlanEndDate    = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).AddDays(1),
                        ParentId       = "0",
                        RelGroup       = "Process",
                        IsRelativeTask = true,
                        TenantId       = project.TenantId,
                        TaskId         = Guid.NewGuid().ToString()
                    };
                    await schedulerTaskManager.InsertAsync(processWrapperTask);
                }
                //2.生成零件节点
                //删除不存在的零件
                //oriTasks.Where(o => o.GetPropertyValue<int?>("PartId") != null && !parts.Select(p => p.Id).ToList().Contains(o.GetPropertyValue<int>("PartId")))
                //    .ToList()
                //    .ForEach(o => SchedulerTaskManager.Repository.HardDelete(o));
                foreach (var part in parts)
                {
                    var partTask = oriTasks.Where(o => o.ParentId == processWrapperTask.TaskId)
                                   .Where(o => o.RelGroup == "Process" && o.RelType == "Part")
                                   .Where(o => o.RelData == part.Id.ToString())
                                   .FirstOrDefault();
                    if (partTask == null)
                    {
                        partTask = new SchedulerTask()
                        {
                            ProjectId      = projectId,
                            ParentId       = processWrapperTask.TaskId,
                            IsRelativeTask = true,
                            RelGroup       = "Process",
                            RelType        = "Part",
                            RelData        = part.Id.ToString(),
                            TaskId         = Guid.NewGuid().ToString(),
                            TenantId       = project.TenantId,
                        };
                        await schedulerTaskManager.InsertAsync(partTask);
                    }
                    partTask.TaskName = part.PartName;
                    partTask.TaskType = "project";
                    if (part.ProcessTasks.Count > 0)
                    {
                        partTask.PlanStartDate = part.ProcessTasks.Min(o => o.SchedulePlanStartDate);
                        partTask.PlanEndDate   = part.ProcessTasks.Max(o => o.SchedulePlanEndDate);
                    }


                    //3.生成任务节点
                    foreach (var processInfo in part.ProcessTasks)
                    {
                        var processTask = oriTasks.Where(o => o.ParentId == partTask.TaskId)
                                          .Where(o => o.RelGroup == "Process" && o.RelType == "ProcessTask")
                                          .Where(o => o.RelData == processInfo.Id.ToString())
                                          .FirstOrDefault();
                        if (processTask == null)
                        {
                            processTask = new SchedulerTask()
                            {
                                ProjectId      = projectId,
                                TaskType       = "task",
                                ParentId       = partTask.TaskId,
                                IsRelativeTask = true,
                                RelGroup       = "Process",
                                RelType        = "ProcessTask",
                                RelData        = processInfo.Id.ToString(),
                                TaskId         = Guid.NewGuid().ToString(),
                                TenantId       = project.TenantId,
                            };
                            await schedulerTaskManager.InsertAsync(processTask);
                        }
                        processTask.TaskName      = processInfo.ProcessType.ProcessTypeName;
                        processTask.PlanStartDate = processInfo.SchedulePlanStartDate;
                        processTask.PlanEndDate   = processInfo.SchedulePlanEndDate;
                        processTask.StartDate     = processInfo.StartDate;
                        processTask.EndDate       = processInfo.EndDate;
                        processTask.Progress      = processInfo.Progress;
                    }
                }
            }
        }
Exemple #24
0
        private static void doorTimer_Elapsed( SchedulerTask task )
        {
            DoorInfo info = ( DoorInfo )task.UserState;
            int counter = 0;
            for ( int x = info.Door.Range.Xmin; x <= info.Door.Range.Xmax; x++ ) {
                for ( int y = info.Door.Range.Ymin; y <= info.Door.Range.Ymax; y++ ) {
                    for ( int z = info.Door.Range.Zmin; z <= info.Door.Range.Zmax; z++ ) {
                        info.WorldMap.QueueUpdate( new BlockUpdate( null, new Vector3I( x, y, z ), info.Buffer[counter] ) );
                        counter++;
                    }
                }
            }

            lock ( openDoorsLock ) { openDoors.Remove( info.Door ); }
        }
Exemple #25
0
        public static void Interval(SchedulerTask task)
        {
            //check to stop Interval
            if (world_ == null)
            {
                task.Stop();
                return;
            }
            if (world_.gameMode != GameMode.FFA) //bug checking
            {
                task.Stop();
                world_ = null;
                return;
            }

            //remove announcement after 5 seconds
            if ((DateTime.Now - announced).TotalSeconds >= 5)
            {
                foreach (Player p in world_.Players)
                {
                    if (p.usesCPE)
                    {
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&f"));//super hacky way to remove announcement, simply send a color code and call it a day
                    }
                }
            }

            if (!started)                       //first time running the interval
            {
                if (world_.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
                {
                    world_.Players.Message("&WFFA&s requires at least 2 people to play.", 0);
                    task.Stop();
                    return;
                }
                if (startTime != null && (DateTime.Now - startTime).TotalSeconds > timeDelay)
                {
                    foreach (Player p in world_.Players)
                    {
                        int x  = rand.Next(2, world_.Map.Width);
                        int y  = rand.Next(2, world_.Map.Length);
                        int z1 = 0;
                        for (int z = world_.Map.Height - 1; z > 0; z--)
                        {
                            if (world_.Map.GetBlock(x, y, z) != Block.Air)
                            {
                                z1 = z + 3;
                                break;
                            }
                        }
                        p.TeleportTo(new Position(x, y, z1 + 2).ToVector3I().ToPlayerCoords()); //teleport players to a random position
                        InitializePlayer(p);
                        if (!p.GunMode)
                        {
                            p.GunMode = true; //turns on gunMode automatically if not already on
                            GunGlassTimer timer = new GunGlassTimer(p);
                            timer.Start();
                        }

                        if (p.Info.IsHidden) //unhides players automatically if hidden (cannot shoot guns while hidden)
                        {
                            p.Info.IsHidden = false;
                            Player.RaisePlayerHideChangedEvent(p);
                        }

                        //send an announcement
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&cLet the Games Begin!"));

                        //set player health
                        p.Send(PacketWriter.MakeSpecialMessage((byte)1, "&f[&a--------&f]"));

                        //set leader
                        p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&eCurrent Leader&f: None"));
                    }
                    started = true;   //the game has officially started
                    if (!world_.gunPhysics)
                    {
                        world_.EnableGunPhysics(Player.Console, true); //enables gun physics if they are not already on
                    }
                    lastChecked = DateTime.Now;                        //used for intervals
                    announced   = DateTime.Now;                        //set when the announcement was launched
                    return;
                }
            }

            //check if one of the players has won
            foreach (Player p in world_.Players)
            {
                if (started && startTime != null && (DateTime.Now - startTime).TotalSeconds >= timeDelay && p.Info.gameKillsFFA >= scoreLimit)
                {
                    Stop(p);
                    return;
                }
            }

            //check if time is up
            if (started && startTime != null && (DateTime.Now - startTime).TotalSeconds >= (totalTime))
            {
                Player winner = GetScoreList()[0];
                if (world_.Players.Count() < 2)
                {
                    Stop(winner);
                    return;
                }
                Stop(winner);
                return;
            }

            if (started && (DateTime.Now - lastChecked).TotalSeconds > 10) //check if players left the world, forfeits if no players of that team left
            {
                if (world_.Players.Count() < 2)
                {
                    Player[] players = world_.Players;
                    Stop(players[0]);
                    return;
                }
            }
            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.Now - startTime).ToSeconds()));
            //Keep the players updated about the score
            if (lastChecked != null && (DateTime.Now - lastChecked).TotalSeconds > 29.9 && timeLeft <= timeLimit)
            {
                Player leader      = GetScoreList()[0]; //leader is the top of the score list
                Player secondPlace = GetScoreList()[1]; //second place is - well, second place XD
                if (isOn() && leader.Info.gameKillsFFA != secondPlace.Info.gameKillsFFA)
                {
                    world_.Players.Message("{0}&f is winning &c{1} &fto &c{2}", 0, leader.ClassyName, leader.Info.gameKillsFFA, secondPlace.Info.gameKillsFFA);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", 0, timeLeft);
                }
                if (leader.Info.gameKillsFFA == secondPlace.Info.gameKillsFFA)
                {
                    world_.Players.Message("{1}&f and {2}&f are tied at &c{0}!", 0, leader.Info.gameKillsFFA, leader.ClassyName, secondPlace.ClassyName);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", 0, timeLeft);
                }
                lastChecked = DateTime.Now;
            }
            if (timeLeft < 10.1)
            {
                world_.Players.Message("&WOnly 10 seconds left!", 0);
            }
        }
Exemple #26
0
        public static void Custom(int limit, int delay)
        {
            world_.Hax = false;
            foreach (Player pl in world_.Players)
            {
                pl.JoinWorld(world_, WorldChangeReason.Rejoin);
            }
            // world_.Players.Send(PacketWriter.MakeHackControl(0, 0, 0, 0, 0, -1)); Commented out until classicube clients support hax packet
            timeDelay = delay;
            timeLimit = limit;

            world_.gameMode = GameMode.Infection;
            stopwatch.Reset();
            stopwatch.Start();
            Scheduler.NewTask(t => world_.Players.Message("&WInfection &fwill be starting in {0} seconds: &WGet ready!", (timeDelay - stopwatch.Elapsed.Seconds))).RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10), 2);
            if (stopwatch.Elapsed.Seconds > 11)
            {
                stopwatch.Stop();
            }
            task_ = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromSeconds(1));
        }
Exemple #27
0
        private static void CheckGrassQueue(SchedulerTask task)
        {
            try
            {
                if (checkGrassQueue != null)
                {
                    if (checkGrassQueue.ThreadState != ThreadState.Stopped)
                    {
                        return;
                    }
                }
                checkGrassQueue = new Thread(new ThreadStart(delegate
                {
                    lock (grassQueue.SyncRoot)
                    {
                        for (int i = 0; i < grassQueue.Count; i++)
                        {
                            GrassUpdate update = (GrassUpdate)grassQueue[i];

                            if (DateTime.Now > update.Scheduled)
                            {
                                try
                                {
                                    if (CanPutGrassOn(update.Block, update.World))
                                    {
                                        BlockUpdate grassUpdate = new BlockUpdate(null, update.Block, Block.Grass);
                                        update.World.Map.QueueUpdate(grassUpdate);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger.Log(LogType.Error, "Physics.CheckGrassQueue: " + ex);
                                }
                                finally
                                {
                                    grassQueue.Remove(update);
                                }
                            }
                        }
                    }
                }));
                checkGrassQueue.Start();
            }
            catch (Exception ex)
            {
                Logger.Log(LogType.Error, "Physics.CheckGrassQueue: " + ex);
            }
        }
Exemple #28
0
 static void MonitorProcessorUsage(SchedulerTask task)
 {
     TimeSpan newCPUTime = Process.GetCurrentProcess().TotalProcessorTime - cpuUsageStartingOffset;
     CPUUsageLastMinute = (newCPUTime - oldCPUTime).TotalSeconds /
                          (Environment.ProcessorCount * DateTime.UtcNow.Subtract(lastMonitorTime).TotalSeconds);
     lastMonitorTime = DateTime.UtcNow;
     CPUUsageTotal = newCPUTime.TotalSeconds /
                     (Environment.ProcessorCount * DateTime.UtcNow.Subtract(StartTime).TotalSeconds);
     oldCPUTime = newCPUTime;
     IsMonitoringCPUUsage = true;
 }
Exemple #29
0
 static void ShowRandomAnnouncement(SchedulerTask task)
 {
     if (!File.Exists(Paths.AnnouncementsFileName)) return;
     string[] lines = File.ReadAllLines(Paths.AnnouncementsFileName);
     if (lines.Length == 0) return;
     string line = lines[new Random().Next(0, lines.Length)].Trim();
     if (line.Length == 0) return;
     foreach (Player player in Players.Where(player => player.World != null))
     {
         player.Message("&R" + ReplaceTextKeywords(player, line));
     }
 }
        public DiscussionViewModel CreateDiscussion(DiscussionViewModel discussion, int? currentClientId, int? currentProviderId, string loggedUserId)
        {
            var newDiscussion = new Discussion
            {
                Date = discussion.Date,
                SubjectOfDiscussion = discussion.SubjectOfDiscussion,
                Summary = discussion.Summary,
                Type = discussion.Type,
                NextDiscussionDate = discussion.NextDiscussionDate,
                NextDiscussionNote = discussion.NextDiscussionNote,
                NextDiscussionType = discussion.NextDiscussionType,
                UserId = loggedUserId,
                Comments = discussion.Comments,
                IsFinished = false,
                IsVisible = discussion.IsVisible
            };

            if (currentClientId != null)
            {
                newDiscussion.ClientId = currentClientId;
                newDiscussion.ProviderId = null;
                newDiscussion.Provider = null;
            }
            else if (currentProviderId != null)
            {
                newDiscussion.ProviderId = currentProviderId;
                newDiscussion.ClientId = null;
                newDiscussion.Client = null;
            }

            this.Data.Discussions.Add(newDiscussion);

            var user = this.Data.Users
                .GetById(loggedUserId);

            var schedulerTask = new SchedulerTask()
            {
                Title = discussion.SubjectOfDiscussion,
                Start = discussion.Date,
                End = discussion.Date,
                Description = discussion.Summary,
                IsAllDay = true,
                StartTimezone = null,
                EndTimezone = null,
                RecurrenceRule = null,
                RecurrenceException = null,
                RecurrenceId = null,
                UserId = loggedUserId,
                IsFinished = false
            };

            user.SchedulerTasks.Add(schedulerTask);

            this.Data.SaveChanges();

            discussion.Id = newDiscussion.Id;

            return discussion;
        }
        public async System.Threading.Tasks.Task RescheduleTaskById(Guid id)
        {
            SchedulerTask schedulerTask = await GetTask(id);

            await _scheduler.RescheduleTask(schedulerTask);
        }
 public static async Task RescheduleTask(this IScheduler scheduler, SchedulerTask task)
 {
     await UnscheduleTask(scheduler, task);
     await ScheduleTask(scheduler, task);
 }
Exemple #33
0
 public override void Load(bool startup)
 {
     task = Server.MainScheduler.QueueRepeat(RainbowCallback, null,
                                             TimeSpan.FromMilliseconds(100));
 }
Exemple #34
0
        protected override void Seed(SpamTools.lib.Data.DataBaseContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            context.Senders.AddOrUpdate(
                new Sender {
                Name = "Ivanov", Adress = "*****@*****.**", Id = 1
            },
                new Sender {
                Name = "Petrov", Adress = "*****@*****.**", Id = 2
            },
                new Sender {
                Name = "Sidorov", Adress = "*****@*****.**", Id = 3
            },
                new Sender {
                Name = "Ya", Adress = "*****@*****.**", Password = PasswordService.Encode("password"), Id = 4
            }
                );

            context.Recipients.AddOrUpdate(
                new Recipient {
                Id = 1, Name = "Recipient 1", Adress = "*****@*****.**"
            },
                new Recipient {
                Id = 2, Name = "Recipient 2", Adress = "*****@*****.**"
            },
                new Recipient {
                Id = 3, Name = "Recipient 3", Adress = "*****@*****.**"
            }
                );

            context.Servers.AddOrUpdate(new MailServer {
                Id = 1, Adress = "smtp.yandex.ru", Port = 465, UseSSL = true
            });
            context.Mails.AddOrUpdate(new Mail("test subject", "test body"));

            SchedulerTask task = new SchedulerTask()
            {
                DateTime   = DateTime.Now,
                Mail       = new Mail("testsubject", "test body"),
                MailServer = new MailServer("mail.server.com"),
                Title      = "title",
                Sender     = new Sender()
                {
                    Id = 555, Adress = "*****@*****.**", Name = "Test Sender"
                },
                Recipients = new[]
                {
                    new Recipient()
                    {
                        Name = "test recipient", Adress = "*****@*****.**"
                    }
                }
            };

            context.SchedulerTask.AddOrUpdate(task);
            context.SaveChanges();
        }
 public static void TaskCallback(SchedulerTask schedulerTask)
 {
     MaintenanceCommands.DoAutoRankAll(Player.Console, PlayerDB.GetPlayerListCopy(), false, "~AutoRank");
 }
Exemple #36
0
        public static void Interval(SchedulerTask task)
        {
            //check to stop Interval
            if (world_ == null)
            {
                task.Stop();
                return;
            }
            if (world_.gameMode != GameMode.TeamDeathMatch)
            {
                task.Stop();
                world_ = null;
                return;
            }

            //remove announcement after 5 seconds
            if ((DateTime.Now - announced).TotalSeconds >= 5)
            {
                foreach (Player p in world_.Players)
                {
                    if (p.usesCPE)
                    {
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&f"));//super hacky way to remove announcement, simply send a color code and call it a day
                    }
                }
            }

            if (!started)
            {
                if (world_.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
                {
                    world_.Players.Message("&WTeam DeathMatch&s requires at least 2 people to play.", MessageType.Chat);
                    return;
                }
                if (startTime != null && (DateTime.Now - startTime).TotalSeconds > timeDelay)
                {
                    foreach (Player p in world_.Players)
                    {
                        if (!manualTeams)
                        {
                            AssignTeams(p); //assigns teams (who knew?)
                        }
                        if (p.Info.isOnRedTeam)
                        {
                            p.TeleportTo(TeamDeathMatch.redSpawn);
                        }                                                                  //teleport players to the team spawn
                        if (p.Info.isOnBlueTeam)
                        {
                            p.TeleportTo(TeamDeathMatch.blueSpawn);
                        }

                        if (!p.GunMode)
                        {
                            p.GunMode = true; //turns on gunMode automatically if not already on
                            GunGlassTimer timer = new GunGlassTimer(p);
                            timer.Start();
                        }

                        if (p.Info.IsHidden) //unhides players automatically if hidden (cannot shoot guns while hidden)
                        {
                            p.Info.IsHidden = false;
                            Player.RaisePlayerHideChangedEvent(p);
                        }

                        //send an announcement
                        p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&cLet the Games Begin!"));

                        if (p.usesCPE)
                        {
                            //set player's health
                            p.Send(PacketWriter.MakeSpecialMessage((byte)1, "&f[&a--------&f]"));

                            //set game score
                            p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&cRed&f: 0,&1 Blue&f: 0"));
                        }
                    }
                    started = true;   //the game has officially started
                    isOn    = true;
                    if (!world_.gunPhysics)
                    {
                        world_.EnableGunPhysics(Player.Console, true); //enables gun physics if they are not already on
                    }
                    lastChecked = DateTime.Now;                        //used for intervals
                    announced   = DateTime.Now;                        //set when the announcement was launched
                    return;
                }
            }

            //check if one of the teams have won
            if (redScore >= scoreLimit || blueScore >= scoreLimit)
            {
                Stop(null);
                return;
            }
            if (blueScore == scoreLimit && redScore == scoreLimit) //if they somehow manage to tie which I am pretty sure is impossible
            {
                world_.Players.Message("The teams tied at {0}!", MessageType.Announcement, redScore);
                Stop(null);
                return;
            }

            //check if time is up
            if (started && startTime != null && (DateTime.Now - startTime).TotalSeconds >= (totalTime))
            {
                if (redScore != blueScore)
                {
                    Stop(null);
                    return;
                }
                if (redScore == blueScore)
                {
                    world_.Players.Message("&fThe teams tied {0} to {1}!", MessageType.Announcement, blueScore, redScore);
                    Stop(null);
                    return;
                }
                if (world_.Players.Count() <= 1)
                {
                    Stop(null);
                    return;
                }
            }

            if (started && (DateTime.Now - lastChecked).TotalSeconds > 10) //check if players left the world, forfeits if no players of that team left
            {
                int redCount  = world_.Players.Where(p => p.Info.isOnRedTeam).ToArray().Count();
                int blueCount = world_.Players.Where(p => p.Info.isOnBlueTeam).ToArray().Count();
                if (blueCount < 1 || redCount < 1)
                {
                    if (blueTeamCount == 0)
                    {
                        if (world_.Players.Any())
                        {
                            world_.Players.Message("&1Blue Team &fhas forfeited the game. &cRed Team &fwins!", MessageType.Announcement);
                        }
                        Stop(null);
                        return;
                    }
                    if (redTeamCount == 0)
                    {
                        if (world_.Players.Any())
                        {
                            world_.Players.Message("&cRed Team &fhas forfeited the game. &1Blue Team &fwins!", MessageType.Announcement);
                        }
                        Stop(null);
                        return;
                    }
                    else
                    {
                        Stop(null);
                        return;
                    }
                }
            }
            timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.Now - startTime).TotalSeconds));
            //Keep the players updated about the score
            if ((DateTime.Now - lastChecked).TotalSeconds > 29.8 && timeLeft <= timeLimit)
            {
                if (redScore > blueScore)
                {
                    world_.Players.Message("&fThe &cRed Team&f is winning {0} to {1}.", MessageType.Announcement, redScore, blueScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", MessageType.Announcement, timeLeft);
                }
                if (redScore < blueScore)
                {
                    world_.Players.Message("&fThe &1Blue Team&f is winning {0} to {1}.", MessageType.Announcement, blueScore, redScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", MessageType.Announcement, timeLeft);
                }
                if (redScore == blueScore)
                {
                    world_.Players.Message("&fThe teams are tied at {0}!", MessageType.Announcement, blueScore);
                    world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", MessageType.Announcement, timeLeft);
                }
                lastChecked = DateTime.Now;
            }
            if (timeLeft == 10)
            {
                world_.Players.Message("&WOnly 10 seconds left!", MessageType.Announcement);
            }
        }
Exemple #37
0
        static void TrainInvincibleCallback(SchedulerTask task)
        {
            Player p = (Player)task.State;

            p.trainInvincible = false;
        }
Exemple #38
0
 internal static void StartSaveTask()
 {
     saveTask = Scheduler.NewBackgroundTask(SaveTask)
                .RunForever(SaveInterval, SaveInterval + TimeSpan.FromSeconds(15));
 }
Exemple #39
0
        static void AllowMoreTntTask(SchedulerTask task)
        {
            TWData data = (TWData)task.State;

            data.TNTCounter--;
        }
Exemple #40
0
 public static void StartSaveTask()
 {
     SchedulerTask saveTask = Scheduler.NewBackgroundTask(delegate { Save(); }).RunForever(SaveInterval, SaveInterval + TimeSpan.FromSeconds(15));
 }
Exemple #41
0
        public static void Start()
        {
            timeLimit = 300;//reset variables incase of a server using custom and then start
            timeDelay = 20;

            world_.Hax = false;
            foreach (Player pl in world_.Players)
            {
                pl.JoinWorld(world_, WorldChangeReason.Rejoin);
            }
            //world_.Players.Send(PacketWriter.MakeHackControl(0,0,0,0,0,-1)); Commented out until classicube clients support hax packet
            stopwatch.Reset();
            stopwatch.Start();
            world_.gameMode = GameMode.Infection;
            delayTask = Scheduler.NewTask(t => world_.Players.Message("&WInfection &fwill be starting in {0} seconds: &WGet ready!", (timeDelay - stopwatch.Elapsed.Seconds)));
            delayTask.RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10), (int)Math.Floor((double)(timeDelay/10)));//Start task immediately, send message every 10s
            if (stopwatch.Elapsed.Seconds > 11)
            {
                stopwatch.Stop();
            }
        }
Exemple #42
0
 internal static void TaskCallback( SchedulerTask schedulerTask ) {
     if( !ConfigKey.AutoRankEnabled.Enabled() ) return;
     PlayerInfo[] onlinePlayers = Server.Players.Select( p => p.Info ).ToArray();
     DoAutoRankAll( Player.AutoRank, onlinePlayers, "(AutoRanked)", true );
 }
Exemple #43
0
 private async Task ExecuteTask(SchedulerTask task, CancellationToken Cancel)
 {
 }
Exemple #44
0
        /// <summary>
        /// Sets a bot, as well as the bot values. Must be called before any other bot classes.
        /// </summary>
        public void setBot(String botName, Level botWorld, Position pos, int entityID)
        {
            Name = botName;
            World = botWorld;
            Position = pos;
            ID = entityID;

            thread = Scheduler.NewTask(t => NetworkLoop());
            thread.RunForever(TimeSpan.FromSeconds(0.1));//run the network loop every 0.1 seconds

            Server.Bots.Add(this);
        }
Exemple #45
0
 private void TaskExited(SchedulerTask task)
 {
     mPendingTasks.Remove(task);
     mPendingFixedUpdateTasks.Remove(task);
 }
Exemple #46
0
 void SchedulerRun3(SchedulerTask ThisTask)
 {
     //Console.WriteLine("SchedulerRun3 " + Time.NowMillis);
     SchedulerRun3Count++;
 }
Exemple #47
0
 static void SaveTask(SchedulerTask task)
 {
     Save();
 }
Exemple #48
0
 static void CheckConnections(SchedulerTask param)
 {
     TcpListener listenerCache = listener;
     if (listenerCache != null && listenerCache.Pending())
     {
         try
         {
             Player.StartSession(listenerCache.AcceptTcpClient());
         }
         catch (Exception ex)
         {
             Logger.Log(LogType.Error,
                         "Server.CheckConnections: Could not accept incoming connection: {0}", ex);
         }
     }
 }
Exemple #49
0
        private void ExecuteScheduledTask(SchedulerTask taskDb)
        {
            int attempts = 0;
            var executor = repo.GetTaskExecutor(taskDb.TaskExecutorId);

            Console.WriteLine($"***** Execute scheduled task [{taskDb.TaskId}] *****");
            taskDb = repo.StartTask(taskDb);
            while (true)
            {
                Console.WriteLine($"***** Run TaskExecutor '{executor.Name}' *****");
                if (!taskExecutors.ContainsKey(executor.CodeClass))
                {
                    Console.WriteLine($"Couldn't run TaskExecutor '{executor.Name}', codeClass of executor '{executor.CodeClass}' is unknown.");
                    throw new Exception("Unknown Task Executor");
                }

                var taskExecutor = taskExecutors[executor.CodeClass];
                var task         = Task.Factory.StartNew(async() =>
                {
                    while (true)
                    {
                        taskDb.StartTime = DateTime.Now;
                        try
                        {
                            var result = await taskExecutor.Execute().TimeoutAfter(executor.TimeOut, taskExecutor);
                            if (result.IsFailed)
                            {
                                throw new Exception(result.FailedReason);
                            }
                            taskDb.Status     = TaskStatus.Finished;
                            taskDb.StartTime  = result.StartTime;
                            taskDb.EndTime    = result.EndTime;
                            taskDb.UpdateDb   = result.UpdateDb;
                            taskDb.FailReason = result.FailedReason;
                            taskDb.Result     = result.IsFailed
                                ? Server.Database.SchedulerData.TaskResult.Failed
                                : Server.Database.SchedulerData.TaskResult.Succeed;
                            repo.UpdateTask(taskDb);
                            CreateTriggeredTasks(executor.TaskExecutorId, result.UpdateDb);
                            return;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"TaskExecutor run fails. Retry attempts {attempts++} from {executor.MaxRetries}. Exception: {ex.Message}");
                            if (attempts > executor.MaxRetries)
                            {
                                taskDb.Status     = TaskStatus.Finished;
                                taskDb.EndTime    = DateTime.Now;
                                taskDb.UpdateDb   = false;
                                taskDb.FailReason = ex.Message;
                                taskDb.Result     = Server.Database.SchedulerData.TaskResult.Failed;
                                repo.UpdateTask(taskDb);
                                CreateTriggeredTasks(executor.TaskExecutorId, false);
                                return;
                            }
                            Task.Delay(EXCEPTION_DELAY).Wait();
                        }
                    }
                }, TaskCreationOptions.AttachedToParent).Unwrap();

                tasks.Push(task);
                break;
            }
        }
Exemple #50
0
        static void CheckIdles(SchedulerTask task)
        {
            Player[] tempPlayerList = Players;
            for (int i = 0; i < tempPlayerList.Length; i++)
            {
                Player player = tempPlayerList[i];
                if (player.Info.Rank.IdleKickTimer <= 0) continue;

                if (player.IdleTime.TotalMinutes >= player.Info.Rank.IdleKickTimer)
                {
                    Message("{0}&S was kicked for being idle for {1} min",
                             player.ClassyName,
                             player.Info.Rank.IdleKickTimer);
                    string kickReason = "Idle for " + player.Info.Rank.IdleKickTimer + " minutes";
                    player.Kick(Player.Console, kickReason, LeaveReason.IdleKick, false, true, false);
                    player.ResetIdleTimer(); // to prevent kick from firing more than once
                }
            }
        }
Exemple #51
0
        public Task <TaskResult> Execute()
        {
            token     = tokenSource.Token;
            taskRepo  = new SchedulerDataRepository();
            gamesRepo = new LeagueDataRepository();

            return(Task.Run(() =>
            {
                var result = new TaskResult
                {
                    StartTime = DateTime.Now
                };

                try
                {
                    var nextGame = gamesRepo.GetNextUpcomingGameDateTime();
                    var lastGathering = taskRepo.GetTimeOfLastExecution(BwinGatheringExecutor);

                    var nextGameNotExist = ConfigurationManager.AppSettings["BwinCoefGatheringDelay_NextGameNotExist"];
                    var nextGameToday = ConfigurationManager.AppSettings["BwinCoefGatheringDelay_NextGameToday"];
                    var nextGameNotToday = ConfigurationManager.AppSettings["BwinCoefGatheringDelay_NextGameNotToday"];

                    var defaultHoursDelay = string.IsNullOrEmpty(nextGameNotExist) ? -2 : -int.Parse(nextGameNotExist);

                    var defaultMinutesShortDelay = string.IsNullOrEmpty(nextGameToday) ? DelayMinutesShort : int.Parse(nextGameToday);
                    var defaultMinutesLongDelay = string.IsNullOrEmpty(nextGameNotToday) ? DelayMinutesLong : int.Parse(nextGameNotToday);


                    if (DateTime.Now.AddHours(defaultHoursDelay) > lastGathering || !lastGathering.HasValue)
                    {
                        lastGathering = DateTime.Now.AddHours(defaultHoursDelay);
                    }

                    var startTime = DateTime.Now;
                    if (nextGame.HasValue)
                    {
                        startTime = (nextGame.Value.Date == DateTime.Now.Date)
                                ? lastGathering.Value.AddMinutes(defaultMinutesShortDelay)
                                : lastGathering.Value.AddMinutes(defaultMinutesLongDelay);
                    }

                    //id could be changed, but name should be consistent
                    var taskExecutorId = taskRepo.GetTaskExecutor(BwinGatheringExecutor).TaskExecutorId;

                    SchedulerTask newTask = new SchedulerTask
                    {
                        TaskExecutorId = taskExecutorId,
                        Status = TaskStatus.Wait,
                        PlanningTime = startTime,
                        UpdateDb = null,
                        Result = null,
                        Type = TaskType.Crawler
                    };
                    result.UpdateDb = taskRepo.AddSchedulerTask(newTask);
                }
                catch (Exception ex)
                {
                    result.IsFailed = true;
                    result.FailedReason = ex.Message;
                }

                result.IsFailed = false;
                result.EndTime = DateTime.Now;
                return result;
            }, token));
        }
Exemple #52
0
 public static Infection GetInstance(World world)
 {
     if (instance == null)
     {
         world_ = world;
         instance = new Infection();
         startTime = DateTime.Now;
         task_ = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromMilliseconds(250)); //run loop every quarter second
     }
     return instance;
 }