3

I've seen a lot of examples that shows how I can run a task using the RX framework by timer e.g.,

var timer = Observable
            .Timer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3))
            .Subscribe(q =>
                {   
                    Console.WriteLine("do something here " + q);
                });

I would like to know if it's possible, and if so, how can I use the RX framework to run a task by schedule, for e.g., every day at 12 midnight.

4

2 回答 2

6

你写的基本上就是它。使用开始时间为Timera 的重载:DateTimeOffset

DateTimeOffset startTime = midnight;
TimeSpan interval = TimeSpan.FromDays(1);

var timer = Observable.Timer(startTime, interval).Subscribe(q => Console.WriteLine("do something"));
于 2013-08-13T13:05:39.713 回答
3

尽管我很喜欢 RX,但我怀疑它是适合这项工作的错误工具。您需要的是Windows 任务计划,它是一种操作系统服务。这有点像 Unixcron服务。您将计划编写为 XML 文件,例如

<?xml version="1.0" ?>
<!--
This sample schedules a task to start on a daily basis.
-->
<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
    <RegistrationInfo>
        <Date>2005-10-11T13:21:17-08:00</Date>
        <Author>AuthorName</Author>
        <Version>1.0.0</Version>
        <Description>Notepad starts every day.</Description>
    </RegistrationInfo>
    <Triggers>
        <CalendarTrigger>
            <StartBoundary>2005-10-11T13:21:17-08:00</StartBoundary>
            <EndBoundary>2006-01-01T00:00:00-08:00</EndBoundary>
            <Repetition>
                <Interval>PT1M</Interval>
                <Duration>PT4M</Duration>
            </Repetition>
            <ScheduleByDay>
                <DaysInterval>1</DaysInterval>
            </ScheduleByDay>
        </CalendarTrigger>
    </Triggers>
    <Principals>
        <Principal>
            <UserId>Administrator</UserId>
            <LogonType>InteractiveToken</LogonType>
        </Principal>
    </Principals>
    <Settings>
        <Enabled>true</Enabled>
        <AllowStartOnDemand>true</AllowStartOnDemand>
        <AllowHardTerminate>true</AllowHardTerminate>
    </Settings>
    <Actions>
        <Exec>
            <Command>notepad.exe</Command>
        </Exec>
    </Actions>
</Task>

安排每日notepad.exe 运行运行。显然,您可以用notepade.exe您选择的应用程序替换,包括用 C# 编写的应用程序。

为什么不使用 RX 来执行此操作。鉴于这是一个需要非常长时间运行且不会崩溃的应用程序,最好将其委托给由操作系统控制的专门服务。

于 2013-08-14T05:00:36.137 回答