Provides a way to create and manage publicly-announced countdowns. Long timers announce once an hour (e.g. "7h left"). During the last hour, timer announces more often: every 10 minutes, then every minute, then every 10 seconds, and finally every second - until the timer is up.
예제 #1
0
 private static void RemoveTimerFromList( [NotNull] ChatTimer timer ) {
     if ( timer == null )
         throw new ArgumentNullException( "timer" );
     lock ( TimerListLock ) {
         Timers.Remove( timer.Id );
     }
 }
예제 #2
0
        static void TimerCallback([NotNull] SchedulerTask task)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            ChatTimer timer = (ChatTimer)task.UserState;

            if (task.MaxRepeats == 1)
            {
                if (String.IsNullOrEmpty(timer.Message))
                {
                    Chat.SendSay(Player.Console, "(Timer Up)");
                }
                else
                {
                    Chat.SendSay(Player.Console, "(Timer Up) " + timer.Message);
                }
                timer.Stop(false);
            }
            else if (timer.announceIntervalIndex >= 0)
            {
                if (timer.lastHourAnnounced != (int)timer.TimeLeft.TotalHours)
                {
                    timer.lastHourAnnounced = (int)timer.TimeLeft.TotalHours;
                    timer.Announce(TimeSpan.FromHours(Math.Ceiling(timer.TimeLeft.TotalHours)));
                }
                if (timer.TimeLeft <= AnnounceIntervals[timer.announceIntervalIndex])
                {
                    timer.Announce(AnnounceIntervals[timer.announceIntervalIndex]);
                    timer.announceIntervalIndex--;
                }
            }
        }
예제 #3
0
 private static void AddTimerToList( [NotNull] ChatTimer timer ) {
     if ( timer == null )
         throw new ArgumentNullException( "timer" );
     lock ( TimerListLock ) {
         Timers.Add( timer.Id, timer );
     }
 }
예제 #4
0
 public ChatTimerEventArgs([NotNull] ChatTimer timer)
 {
     if (timer == null)
     {
         throw new ArgumentNullException("timer");
     }
     Timer = timer;
 }
예제 #5
0
        static void RaiseStoppedEvent(ChatTimer timer)
        {
            var h = Stopped;

            if (h != null)
            {
                h(null, new ChatTimerEventArgs(timer));
            }
        }
예제 #6
0
        static void RaiseStartedEvent([NotNull] ChatTimer timer)
        {
            var h = Started;

            if (h != null)
            {
                h(null, new ChatTimerEventArgs(timer));
            }
        }
예제 #7
0
        /// <summary> Starts this timer with the specified duration, and end message. </summary>
        /// <param name="duration"> Amount of time the timer should run before completion. Should not be less than ChatTimer.MinDuration. </param>
        /// <param name="message"> Message to display when timer reaches zero. May be null. </param>
        /// <param name="startedBy"> Name of player who started timer. May not be null. </param>
        /// <returns> Newly-created, and already-started timer. </returns>
        /// <exception cref="ArgumentNullException"> startedBy is null. </exception>
        /// <exception cref="ArgumentOutOfRangeException"> duration is less than ChatTimer.MinDuration. </exception>
        public static ChatTimer Start(TimeSpan duration, [CanBeNull] string message, [NotNull] string startedBy)
        {
            if (startedBy == null)
            {
                throw new ArgumentNullException("startedBy");
            }
            if (duration < MinDuration)
            {
                throw new ArgumentException("Timer duration should be at least 1s", "duration");
            }
            ChatTimer newTimer = new ChatTimer(duration, message, startedBy);

            RaiseStartedEvent(newTimer);
            return(newTimer);
        }
예제 #8
0
        static void TimerCallback([NotNull] SchedulerTask task)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            ChatTimer timer = (ChatTimer)task.UserState;

            if (task.MaxRepeats == 1)
            {
                if (String.IsNullOrEmpty(timer.Message))
                {
                    Server.Players.Message("&2[&7CountDown Finished&2]");
                    IRC.SendChannelMessage("\u212C&S[&7CountDown Finished&S]");
                }
                else
                {
                    Server.Players.Message("&2[&7Timer Finished&2] &7" + timer.Message);
                    IRC.SendChannelMessage("\u212C&S[&7Timer Finished&S]\u211C " + timer.Message);
                }
                //Timer Ends Here.
                timer.Stop(false);
            }
            else if (timer.announceIntervalIndex >= 0)
            {
                if (timer.lastHourAnnounced != (int)timer.TimeLeft.TotalHours)
                {
                    timer.lastHourAnnounced = (int)timer.TimeLeft.TotalHours;
                    timer.Announce(TimeSpan.FromHours(Math.Ceiling(timer.TimeLeft.TotalHours)));
                }
                if (timer.TimeLeft <= AnnounceIntervals[timer.announceIntervalIndex])
                {
                    timer.Announce(AnnounceIntervals[timer.announceIntervalIndex]);
                    timer.announceIntervalIndex--;
                }
            }
        }
예제 #9
0
        static void TimerHandler([NotNull] Player player, [NotNull] CommandReader cmd)
        {
            string param = cmd.Next();

            // List timers
            if (param == null)
            {
                ChatTimer[] list = ChatTimer.TimerList.OrderBy(timer => timer.TimeLeft).ToArray();
                if (list.Length == 0)
                {
                    player.Message("No timers running.");
                }
                else
                {
                    player.Message("There are {0} timers running:", list.Length);
                    foreach (ChatTimer timer in list)
                    {
                        player.Message("  #{0} \"{1}&S\" (started by {2}, {3} left)",
                                       timer.Id,
                                       timer.Message,
                                       timer.StartedBy,
                                       timer.TimeLeft.ToMiniString());
                    }
                }
                return;
            }

            // Abort a timer
            if (param.Equals("abort", StringComparison.OrdinalIgnoreCase))
            {
                int timerId;
                if (cmd.NextInt(out timerId))
                {
                    ChatTimer timer = ChatTimer.FindTimerById(timerId);
                    if (timer == null || !timer.IsRunning)
                    {
                        player.Message("Given timer (#{0}) does not exist.", timerId);
                    }
                    else
                    {
                        timer.Abort();
                        string abortMsg = String.Format("&Y(Timer) {0}&Y aborted a timer with {1} left: {2}",
                                                        player.ClassyName,
                                                        timer.TimeLeft.ToMiniString(),
                                                        timer.Message);
                        Chat.SendSay(player, abortMsg);
                    }
                }
                else
                {
                    CdTimer.PrintUsage(player);
                }
                return;
            }

            // Start a timer
            if (player.Info.IsMuted)
            {
                player.MessageMuted();
                return;
            }
            if (player.DetectChatSpam())
            {
                return;
            }
            TimeSpan duration;

            if (!param.TryParseMiniTimeSpan(out duration))
            {
                CdTimer.PrintUsage(player);
                return;
            }
            if (duration > DateTimeUtil.MaxTimeSpan)
            {
                player.MessageMaxTimeSpan();
                return;
            }
            if (duration < ChatTimer.MinDuration)
            {
                player.Message("Timer: Must be at least 1 second.");
                return;
            }

            string sayMessage;
            string message = cmd.NextAll();

            if (String.IsNullOrWhiteSpace(message))
            {
                sayMessage = String.Format("&Y(Timer) {0}&Y started a {1} timer",
                                           player.ClassyName,
                                           duration.ToMiniString());
            }
            else
            {
                sayMessage = String.Format("&Y(Timer) {0}&Y started a {1} timer: {2}",
                                           player.ClassyName,
                                           duration.ToMiniString(),
                                           message);
            }
            Chat.SendSay(player, sayMessage);
            ChatTimer.Start(duration, message, player.Name);
        }
예제 #10
0
 public ChatTimerEventArgs(ChatTimer timer)
 {
     Timer = timer;
 }
예제 #11
0
파일: ChatTimer.cs 프로젝트: fragmer/fCraft
 public ChatTimerEventArgs( ChatTimer timer ) {
     Timer = timer;
 }
예제 #12
0
        static string TimerFilename(ChatTimer timer)
        {
            DateTime endTime = timer.EndTime;

            return(endTime.Year + "_" + endTime.Month + "_" + endTime.Day + "_" + endTime.Hour + "_" + endTime.Minute + "_" + endTime.Second + ".txt");
        }
예제 #13
0
파일: ChatTimer.cs 프로젝트: fragmer/fCraft
 /// <summary> Starts this timer with the specified duration, and end message. </summary>
 /// <param name="duration"> Amount of time the timer should run before completion. Should not be less than ChatTimer.MinDuration. </param>
 /// <param name="message"> Message to display when timer reaches zero. May be null. </param>
 /// <param name="startedBy"> Name of player who started timer. May not be null. </param>
 /// <returns> Newly-created, and already-started timer. </returns>
 /// <exception cref="ArgumentNullException"> startedBy is null. </exception>
 /// <exception cref="ArgumentOutOfRangeException"> duration is less than ChatTimer.MinDuration. </exception>
 public static ChatTimer Start( TimeSpan duration, [CanBeNull] string message, [NotNull] string startedBy ) {
     if( startedBy == null ) throw new ArgumentNullException( "startedBy" );
     if( duration < MinDuration ) {
         throw new ArgumentException( "Timer duration should be at least 1s", "duration" );
     }
     ChatTimer newTimer = new ChatTimer( duration, message, startedBy );
     RaiseStartedEvent( newTimer );
     return newTimer;
 }
예제 #14
0
        internal static void LoadAll()
        {
            try {
                if (!Directory.Exists("./Timers"))
                {
                    return;
                }

                string[] files = Directory.GetFiles("./Timers");
                foreach (string file in files)
                {
                    if (Path.GetExtension("./Timers/" + file) != ".txt")
                    {
                        continue;
                    }
                    string[] data = File.ReadAllLines(file);

                    DateTime   start   = default(DateTime);
                    DateTime   end     = default(DateTime);
                    PlayerInfo creator = null;
                    string     message = null;

                    foreach (string line in data)
                    {
                        if (line.Contains("StartDate: "))
                        {
                            string date = line.Remove(0, "StartDate: ".Length);
                            DateTime.TryParse(date, out start);
                        }
                        else if (line.Contains("EndDate: "))
                        {
                            string date = line.Remove(0, "EndDate: ".Length);
                            DateTime.TryParse(date, out end);
                        }
                        else if (line.Contains("CreatedBy: "))
                        {
                            string creatorName = line.Remove(0, "CreatedBy: ".Length);
                            creator = PlayerDB.FindPlayerInfoExact(creatorName);
                        }
                        else if (line.Contains("Message: "))
                        {
                            message = line.Remove(0, "Creator: ".Length);
                        }
                    }

                    if (creator == null)
                    {
                        creator = Player.Console.Info;
                    }
                    if (start.Ticks == 0 || end.Ticks == 0 || message == null)
                    {
                        Player.Console.Message("Error starting a Timer: {0}, {1}, {2}, {3}", start, end, creator.Name, message);
                        continue;
                    }

                    if (end < DateTime.UtcNow)
                    {
                        Player.Console.Message("Timer Expired: {0}, {1}, {2}, {3} Time Now: {4}", start, end, creator.Name, message, DateTime.UtcNow);
                        File.Delete(file);
                        continue;
                    }

                    ChatTimer.Start((end - DateTime.UtcNow), message, creator.Name);
                }

                if (files.Length > 0)
                {
                    Player.Console.Message("All Timers Loaded. ({0})", files.Length);
                }
                else
                {
                    Player.Console.Message("No Timers Were Loaded.");
                }
            } catch (Exception ex) {
                Player.Console.Message("Timer Loader Has Crashed: {0}", ex);
            }
        }
예제 #15
0
파일: Server.cs 프로젝트: fragmer/fCraft
 /// <summary> Initiates the server shutdown with given parameters. </summary>
 /// <param name="shutdownParams"> Shutdown parameters </param>
 /// <param name="waitForShutdown"> If true, blocks the calling thread until shutdown is complete or cancelled. </param>
 public static void Shutdown( [NotNull] ShutdownParams shutdownParams, bool waitForShutdown ) {
     if( shutdownParams == null ) throw new ArgumentNullException( "shutdownParams" );
     lock( ShutdownLock ) {
         if( !CancelShutdown() ) return;
         shutdownThread = new Thread( ShutdownThread ) {
             Name = "fCraft.Shutdown",
             CurrentCulture = new CultureInfo( "en-US" )
         };
         if( shutdownParams.Delay >= ChatTimer.MinDuration ) {
             string timerMsg = String.Format( "Server {0} ({1})",
                                              shutdownParams.Restart ? "restart" : "shutdown",
                                              shutdownParams.ReasonString );
             string nameOnTimer;
             if( shutdownParams.InitiatedBy == null ) {
                 nameOnTimer = Player.Console.Name;
             } else {
                 nameOnTimer = shutdownParams.InitiatedBy.Name;
             }
             shutdownTimer = ChatTimer.Start( shutdownParams.Delay, timerMsg, nameOnTimer );
         }
         shutdownThread.Start( shutdownParams );
     }
     if( waitForShutdown ) {
         ShutdownWaiter.WaitOne();
     }
 }
예제 #16
0
파일: Server.cs 프로젝트: fragmer/fCraft
 /// <summary> Attempts to cancel the shutdown timer. </summary>
 /// <returns> True if a shutdown timer was cancelled, false if no shutdown is in progress.
 /// Also returns false if it's too late to cancel (shutdown has begun). </returns>
 public static bool CancelShutdown() {
     lock( ShutdownLock ) {
         if( shutdownThread != null ) {
             if( IsShuttingDown || shutdownThread.ThreadState != ThreadState.WaitSleepJoin ) {
                 return false;
             }
             if( shutdownTimer != null ) {
                 shutdownTimer.Abort();
                 shutdownTimer = null;
             }
             ShutdownWaiter.Set();
             shutdownThread.Abort();
             shutdownThread = null;
         }
     }
     return true;
 }
예제 #17
0
파일: ChatTimer.cs 프로젝트: fragmer/fCraft
 static void RaiseStoppedEvent( ChatTimer timer ) {
     var h = Stopped;
     if( h != null ) h( null, new ChatTimerEventArgs( timer ) );
 }