VisionTimer定时器插件

作者: 傲视三国 | 来源:发表于2016-07-12 14:35 被阅读996次

转载自:http.dsqiu.iteye.com
插件的详解在链接里已经说的很清楚了,这里主要说下我改了一些代码让timer支持时间戳。以及增加了暂停和继续的方法。

先说说支持时间戳的部分:
外部接口加了个参数,用于判断是否需要用时间戳:

// time + callback + [timer handle]
    public static void In(float delay, Callback callback, Handle timerHandle = null, bool isConvertDate = false)
    { Schedule(delay, callback, null, null, timerHandle, 1, -1.0f, isConvertDate); }

获取剩余的时间,用于暂停和继续

    /// <summary>
    /// 读取本地存储时间戳,获取剩余的时间
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static float ContinueStartForConvertDateTime(string key)
    {
        if (PlayerPrefs.GetString("key") == null)
            return -1;
        if (PlayerPrefs.GetString(key) != "" && Int64.Parse(PlayerPrefs.GetString(key)) != 0)
        {
            float time = (Int64.Parse(PlayerPrefs.GetString(key)) - CommonFuntion.ConvertDateTimeForMillise(DateTime.Now)) * 0.001f;
            UnityEngine.Debug.Log("----------------"+ time);
            if (time < 0)
                time = 0;
            return time;
        }
        else
            return -1;
    }

Schedule添加定时器方法中isConvertDate如果是true,定时器用的就是时间戳,同时存储在本地数据中

        if(isConvertDate)
        {
            pauseTime = 0;
            long start = CommonFuntion.ConvertDateTimeForMillise(DateTime.Now);
            long end = CommonFuntion.ConvertDateTimeForMillise(DateTime.Now.AddMilliseconds(time * 1000));
            m_NewEvent.StartTimeDateTime = start;
            m_NewEvent.DueTimeDateTime= end;
            PlayerPrefs.SetString(dataKey, end.ToString());
            UnityEngine.Debug.Log(CommonFuntion.ConvertDateTime(DateTime.Now) + "---------------"+start + "------------"+ end + "----------"+(end- start)*0.001f+"-----"+time);
        }
        else
        {
            m_NewEvent.StartTime = Time.time;
            m_NewEvent.DueTime = Time.time + time;
        }
        m_NewEvent.Iterations = iterations;
        m_NewEvent.Interval = interval;

Update中增加判断时间戳定时器完成条件:

            long start = CommonFuntion.ConvertDateTimeForMillise(DateTime.Now);
            // execute all due events
            if ((Time.time >= vp_Timer.m_Active[m_EventIterator].DueTime && vp_Timer.m_Active[m_EventIterator].DueTime != 0) || // time is up
                vp_Timer.m_Active[m_EventIterator].Id == 0 || (start >= vp_Timer.m_Active[m_EventIterator].DueTimeDateTime && vp_Timer.m_Active[m_EventIterator].DueTimeDateTime != 0))// event has been canceled ('Execute' will kill it)
                vp_Timer.m_Active[m_EventIterator].Execute();

DueTime数据处理的地方也要添加DueTimeDateTime相应的处理:

        private void Recycle()
        {
            Id = 0;
            DueTime = 0.0f;
            //重置时间戳
            if(DueTimeDateTime > 0 && pauseTime <= 0)
                PlayerPrefs.SetString(dataKey, "");
            DueTimeDateTime = 0;

            StartTime = 0.0f;

            Function = null;
            ArgFunction = null;
            Arguments = null;

            if (vp_Timer.m_Active.Remove(this))
                m_Pool.Add(this);

#if (UNITY_EDITOR && DEBUG)
            EditorRefresh();
#endif

        }
        public void Execute()
        {

            // if either 'Id' or 'DueTime' is zero, this timer has been
            // canceled: recycle it!
            if (Id == 0 || (DueTime == 0.0f && DueTimeDateTime == 0))
            {
                Recycle();
                return;
            }

            // attempt to execute the callback function
            if (Function != null)
                Function();
            else if (ArgFunction != null)
                ArgFunction(Arguments);
            else
            {
                // function was null: nothing to do so abort
                Error("Aborted event because function is null.");
                Recycle();
                return;
            }

            // count down to recycling
            if (Iterations > 0)
            {
                Iterations--;
                // usually a timer has one default iteration and will
                // enter the below scope to get recycled right away ...
                if (Iterations < 1)
                {
                    Recycle();
                    return;
                }
            }

            // ... but if we end up here the timer either has atleast one
            // iteration left, or user set iterations to zero for infinite
            // repetition. either way: update due time with the interval
            DueTime = Time.time + Interval;
            DueTimeDateTime = CommonFuntion.ConvertDateTimeForMillise(DateTime.Now.AddMilliseconds(Interval * 1000));
        }

在SchedulingDemo场景中进行测试
SchedulingDemo脚本中我的测试代码:

    void Start()
    {
        float time = vp_Timer.ContinueStartForConvertDateTime(vp_Timer.dataKey);
        PlayerPrefs.SetString(vp_Timer.dataKey, "");
        if (time >= 0)
        {
            StartCoroutine(Test(time));
        }
    }
    IEnumerator Test(float time)
    {
        yield return new WaitForEndOfFrame();
        callback = SmackCube;
        vp_Timer.In(time, callback, 5, 0.5f, null, true);
    }
...
...
        if (DoButton("----10秒后执行----5 iterations of a method, with 0.5 sec intervals"))
        {
            callback = SmackCube;
            vp_Timer.In(10f, SmackCube, 5, 0.5f, null, true);
        }
...
...

运行后

![~GSDIM9XE0NNQ8U1]W5S111.png](https://img.haomeiwen.com/i1239783/9b5515db781b1675.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

关闭后重新运行,实现重新进游戏继续计时。

SQ_DD)H_005%2HWXT2(D$13.png

可以看出时间戳数据我用的都是精确到毫秒的,因为在Update中有获取数据,如果只是精确到秒的话,一下就被判定是完成了。

timer没有封装暂停和继续的方法,但是事件的数据都有封装在Event里,所以加个暂停和继续自然是no problem。。。于是马上动手给他加了一个暂停和继续的方法,我的思路是暂停的时候把活跃的Event列表和剩余时间存起来,继续的时候再用对应的剩余时间去激活,单个事件可以通过MethodName来暂停和继续:
vp_Timer中新增的暂停接口:

    public static void PauseAll(string methodName = "")
    {
        if (methodName != "")
        {
            Event e = m_Active.Find((eventItem) => eventItem.MethodName == methodName);
            if (e == null)
                return;
            e.Paused = true;
            eventPauseList.Add(e);
            //暂停后剩余时间
            float residueTime = e.isConvertDate ? ((e.DueTimeDateTime - CommonFuntion.ConvertDateTimeForMillise(DateTime.Now)) * 0.001f) : (e.DueTime - e.StartTime) - e.LifeTime;
            UnityEngine.Debug.Log(e.MethodName + "-------Pause-------residueTime : " + residueTime);
            pauseTimeList.Add(residueTime);
            DestroyAll(methodName);
        }
        else
        {
            PauseDataSave();
            DestroyAll();
        }
    }
    private static void PauseDataSave()
    {
        for (int t = 0; t < m_Active.Count; t++)
        {
            if (m_Active[t].Paused)
                continue;
            m_Active[t].Paused = true;
            eventPauseList.Add(m_Active[t]);
            //暂停后剩余时间
            float residueTime = m_Active[t].isConvertDate ? ((m_Active[t].DueTimeDateTime - CommonFuntion.ConvertDateTimeForMillise(DateTime.Now)) * 0.001f) : (m_Active[t].DueTime - m_Active[t].StartTime) - m_Active[t].LifeTime;
            UnityEngine.Debug.Log(eventPauseList[t].MethodName + "-------PauseAll-------residueTime : " + residueTime);
            pauseTimeList.Add(residueTime);
        }
    }
    public static void ContiuePlayAll()
    {
        for (int t = 0; t < eventPauseList.Count; t++)
        {
            eventPauseList[t].Paused = false;
            Schedule(pauseTimeList[t], eventPauseList[t].Function, eventPauseList[t].ArgFunction, eventPauseList[t].Arguments, null, eventPauseList[t].Iterations, eventPauseList[t].Interval, eventPauseList[t].isConvertDate);
            UnityEngine.Debug.Log(eventPauseList[t].MethodName + "-------ContiuePlayAll-------pauseTimeList[t] : " + pauseTimeList[t]);
        }
        eventPauseList.Clear();
        pauseTimeList.Clear();
    }

SchedulingDemo脚本中我的测试代码:

        if (GUI.Button(new Rect(Screen.width * 0.85f, Screen.width * 0.2f + Screen.width * 0.05f, Screen.width * 0.04f * 3, Screen.width * 0.04f), "Pause"))
        {
            if (callback != null)
                vp_Timer.PauseAll(callback.Method.Name);
        }
        
        if (GUI.Button(new Rect(Screen.width * 0.85f, Screen.width * 0.25f + Screen.width * 0.05f, Screen.width * 0.04f * 3, Screen.width * 0.04f), "PauseAll"))
        {
            vp_Timer.PauseAll();
        }

        if (GUI.Button(new Rect(Screen.width * 0.85f, Screen.width * 0.3f + Screen.width * 0.05f, Screen.width * 0.04f * 3, Screen.width * 0.04f), "PlayAll"))
        {
            vp_Timer.ContiuePlayAll();
        }

测试结果:


Paste_Image.png

对时间戳定时的因为我有存本地数据,所以暂停和继续只有在运行中有生效。

如果要实现某一个事件在延时几秒后调几次,间隔多少时间这种比较复杂的流程只要1句简短的代码就能搞定,想想是不是还有点小激动呢。

        if (DoButton("----10秒后执行----5 次调用, 间隔 0.5 秒"))
        {
            callback = SmackCube;
            vp_Timer.In(10f, SmackCube, 5, 0.5f, null, true);
        }

这个插件还有做用字符串来标记delegate


Paste_Image.png

今天的内容就到这啦,研究完是不是觉得VisionTimer还蛮给力的呢。

相关文章

  • VisionTimer定时器插件

    转载自:http.dsqiu.iteye.com插件的详解在链接里已经说的很清楚了,这里主要说下我改了一些代码让t...

  • cron定时器插件使用

    cron 表达式的基本格式 用过 linux 的应该对 cron 有所了解。linux 中可以通过 crontab...

  • 2017.12.21学习总结

    下午学习了定时器,定时器分为高级定时器、通用定时器和基本定时器,我们主要研究通用定时器。 定时器中断实现步骤:...

  • 记录一次全屏标题过长滚动显示的开发过程

    1.开始使用marquee,过时了。不可 2,使用定时器操作数组,消耗性格 3,使用插件,出现不显示尾部的问题,改...

  • javascript笔记6

    定时器-间歇性定时器 定时器-延时定时器 认识DOM 间歇性定时器var time = window.setInt...

  • vue 优化方法

    第三方插件按需引入,路由懒加载 v-for v-if 避免一起使用 组件实例销毁时,取消事件监听。清除定时器。 使...

  • 定时器弹框、定时器基本用法、定时器动画、时钟

    定时器弹框: 定时器基本用法: 定时器动画: 时钟:

  • 无标题文章

    iOS NSTimer使用详解-开启、关闭、移除 定时器定时器详解ios定时器关闭定时器NSTimer 1、要使用...

  • 定时器

    1.倒计定时器(setTimeout) clearTimeout清除定时器2.循环定时器(setInterval)...

  • 第十三节 JavaScript 定时器 单线程

    一、定时器 1. JS存在两种定时器 setTimeout() 延迟定时器 setInterval() ...

网友评论

    本文标题:VisionTimer定时器插件

    本文链接:https://www.haomeiwen.com/subject/pyfjjttx.html