[CF Skills]如何在预定的时间运行你的程序

如何在预定的时间运行应用程序呢?就比如一个自定义的闹钟程序。如何在.NET Compact Framework中实现这样一个功能,好的,先来看看从MSDN上可以查到的这样一个函数:

BOOL CeRunAppAtTime(

 TCHAR* pwszAppName,

 SYSTEMTIME* lpTime

}

值得注意的是第二个参数是SystemTime的结构。这在.NET Compact Framwork中转化过来并不是一件直接的事。

        publicstaticvoid RunAppAtTime(string s, DateTime dt)

        {

            //首先将DateTime转化成Windows FileTime(UTC)

            long fileStartTime = dt.ToFileTime();

            long localFileStartTime = 0;

            //然后将UTC file time转成本地file time

            FileTimeToLocalFileTime(ref fileStartTime, ref localFileStartTime);

            SystemTime systemStartTime = newSystemTime();

            //再将本地file time 转化成systemtime结构

            FileTimeToSystemTime(ref localFileStartTime, systemStartTime);

            CeRunAppAtTime(s, systemStartTime);

        }

#region invoke methods

        [DllImport("CoreDLL.dll")]

        publicstaticexternint CeRunAppAtTime(string application,

SystemTime startTime);

        [DllImport("CoreDLL.dll")]

        publicstaticexternint FileTimeToSystemTime(reflong lpFileTime,

SystemTime lpSystemTime);

        [DllImport("CoreDLL.dll")]

        publicstaticexternint FileTimeToLocalFileTime(reflong lpFileTime,

reflong lpLocalFileTime);

#endregion

这样的程序是可以运行的,我们可以用如下的代码测试一下:

            DateTime startTime = DateTime.Now + newTimeSpan(0, 1, 0);

            string s = @""Windows"BubbleBreaker.exe";

            Winbile.AtTime.RunAppAtTime(s,startTime);

可以看到在一分钟以后BubbleBreaker运行起来了,这似乎不错。但是对于长时间间隔的appCall这就行不通了,在大多数机器下,CeRunAppAtTime并不能在长时间间隔下工作(例如机器已经Suspend),那么怎么让程序无论是挂起还是lowpower下都一直运行呢?这时候,可以参考SDF2.1里面提供的一个叫做LargeIntervalTimer的东东,故名思意就是大时间间隔的计时器。用法很简单,指定几个属性就OK了:

         public static void RunAtLargeInterval(EventHandler myhandler)

        {

            OpenNETCF.WindowsCE.LargeIntervalTimer m_lit = new OpenNETCF.WindowsCE.LargeIntervalTimer();

            // 这里设为从今后 1天开始

            m_lit.FirstEventTime = DateTime.Now.AddDays(1);

            // 之后7天一次

            m_lit.Interval = new TimeSpan(7, 0, 0, 0);

            // 反复

            m_lit.OneShot = false;

            // 挂上一个事件处理器

            m_lit.Tick += myhandler; 

            // 启动

            m_lit.Enabled = true;

        }

这样不论是你的自定义的日程表,还是你的GPS纪录器或者其他此类必须长期运行在时间轴上的应用程序就可以顺畅的一直运行了,不必担心机器挂起,也没有任何冗余的代码。你只需要写好自己的EventHandler

完整的代码示例在这里:http://www.winbile.net/bbs/forums/threads/1034915.aspx

posted on 2008-02-03 03:49  J.D Huang  阅读(3078)  评论(4编辑  收藏  举报