- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想创建一个 Windows 服务,它将创建 x 个线程,每 x 分钟唤醒一次并执行一些工作。
我认为任务调度或并行框架不适合这种类型的工作,因为它最适合开始、完成和结束的工作,而不是一成不变的工作。
我应该考虑使用线程池来实现这种方法,还是有人对好的解决方案有任何建议?
最佳答案
真的,听起来您只需要一个线程。
这是我为这类事情创建的帮助程序类。以下是您如何使用它:
class MyPeriodicTasks : PeriodicMultiple
{
// The first task will start 30 seconds after this class is instantiated and started:
protected override TimeSpan FirstInterval { get { return TimeSpan.FromSeconds(30); } }
public MyPeriodicTasks()
{
Tasks = new[] {
new Task { Action = task1, MinInterval = TimeSpan.FromMinutes(5) },
new Task { Action = task2, MinInterval = TimeSpan.FromMinutes(15) },
};
}
private void task1() { /* code that gets executed once every 5 minutes */ }
private void task2() { /* code that gets executed once every 15 minutes */ }
}
然后,开始任务:
var tasks = new MyPeriodicTasks();
tasks.Start();
在服务关闭期间:
tasks.Shutdown();
(或者,使用 backgroundThread: true 调用 Start
,这样您就不需要调用 Shutdown,但是任务可能会在执行某事的过程中终止)
这是实际的代码:
/// <summary>
/// Encapsulates a class performing a certain activity periodically, which can be initiated once
/// and then permanently shut down, but not paused/resumed. The class owns its own separate
/// thread, and manages this thread all by itself. The periodic task is executed on this thread.
/// <para>The chief differences to <see cref="System.Threading.Timer"/> are as follows. This
/// class will never issue overlapping activities, even if an activity takes much longer than the interval;
/// the interval is between the end of the previous occurrence of the activity and the start of the next.
/// The activity is executed on a foreground thread (by default), and thus will complete once started,
/// unless a catastrophic abort occurs. When shutting down the activity, it's possible to wait until the
/// last occurrence, if any, has completed fully.</para>
/// </summary>
public abstract class Periodic
{
private Thread _thread;
private CancellationTokenSource _cancellation;
private ManualResetEvent _exited;
/// <summary>
/// Override to indicate how long to wait between the call to <see cref="Start"/> and the first occurrence
/// of the periodic activity.
/// </summary>
protected abstract TimeSpan FirstInterval { get; }
/// <summary>
/// Override to indicate how long to wait between second and subsequent occurrences of the periodic activity.
/// </summary>
protected abstract TimeSpan SubsequentInterval { get; }
/// <summary>
/// Override with a method that performs the desired periodic activity. If this method throws an exception
/// the thread will terminate, but the <see cref="LastActivity"/> will occur nevertheless.
/// </summary>
protected abstract void PeriodicActivity();
/// <summary>
/// Override with a method that performs an activity on the same thread as <see cref="PeriodicActivity"/> during
/// shutdown, just before signalling that the shutdown is complete. The default implementation of this method
/// does nothing. This method is guaranteed to be called during a shutdown, even if the shutdown is due to an
/// exception propagating outside of <see cref="PeriodicActivity"/>.
/// </summary>
protected virtual void LastActivity() { }
/// <summary>
/// Returns false before the first call to <see cref="Start"/> and after the first call to <see cref="Shutdown"/>;
/// true between them.
/// </summary>
public bool IsRunning { get { return _cancellation != null && !_cancellation.IsCancellationRequested; } }
/// <summary>
/// Schedules the periodic activity to start occurring. This method may only be called once.
/// </summary>
/// <param name="backgroundThread">By default (false) the class will use a foreground thread, preventing application shutdown until the thread has terminated. If true, a background thread will be created instead.</param>
public virtual void Start(bool backgroundThread = false)
{
if (_thread != null)
throw new InvalidOperationException(string.Format("\"Start\" called multiple times ({0})", GetType().Name));
_exited = new ManualResetEvent(false);
_cancellation = new CancellationTokenSource();
_thread = new Thread(threadProc) { IsBackground = backgroundThread };
_thread.Start();
}
private volatile bool _periodicActivityRunning = false;
/// <summary>
/// Causes the periodic activity to stop occurring. If called while the activity is being performed,
/// will wait until the activity has completed before returning. Ensures that <see cref="IsRunning"/>
/// is false once this method returns.
/// </summary>
public virtual bool Shutdown(bool waitForExit)
{
if (waitForExit && _periodicActivityRunning && Thread.CurrentThread.ManagedThreadId == _thread.ManagedThreadId)
throw new InvalidOperationException("Cannot call Shutdown(true) from within PeriodicActivity() on the same thread (this would cause a deadlock).");
if (_cancellation == null || _cancellation.IsCancellationRequested)
return false;
_cancellation.Cancel();
if (waitForExit)
_exited.WaitOne();
return true;
}
private void threadProc()
{
try
{
_cancellation.Token.WaitHandle.WaitOne(FirstInterval);
while (!_cancellation.IsCancellationRequested)
{
_periodicActivityRunning = true;
PeriodicActivity();
_periodicActivityRunning = false;
_cancellation.Token.WaitHandle.WaitOne(SubsequentInterval);
}
}
finally
{
try { LastActivity(); }
finally { _exited.Set(); }
}
}
}
/// <summary>
/// <para>Encapsulates a class performing multiple related yet independent tasks on the same thread
/// at a certain minimum interval each. Schedules the activity that is the most late at every opportunity,
/// but will never execute more than one activity at a time (as they all share the same thread).</para>
/// </summary>
public abstract class PeriodicMultiple : Periodic
{
/// <summary>
/// Used to define the activities to be executed periodically.
/// </summary>
protected sealed class Task
{
/// <summary>The activity to be performed.</summary>
public Action Action;
/// <summary>The mimimum interval at which this activity should be repeated. May be delayed arbitrarily though.</summary>
public TimeSpan MinInterval;
/// <summary>Stores the last time this activity was executed.</summary>
public DateTime LastExecuted;
/// <summary>Calculates by how much this activity has been delayed. Is used internally to pick the next activity to run. Returns negative values for activities that aren't due yet.</summary>
public TimeSpan DelayedBy()
{
if (LastExecuted == default(DateTime))
return TimeSpan.FromDays(1000) - MinInterval; // to run shortest interval first when none of the tasks have ever executed
else
return (DateTime.UtcNow - LastExecuted) - MinInterval;
}
}
/// <summary>If desired, override to provide a custom interval at which the scheduler
/// should re-check whether any activity is due to start. Defaults to 1 second.</summary>
protected override TimeSpan SubsequentInterval { get { return TimeSpan.FromSeconds(1); } }
/// <summary>Initialise this with the list of activities to be executed.</summary>
protected IList<Task> Tasks;
/// <summary>For internal use.</summary>
protected sealed override void PeriodicActivity()
{
TimeSpan maxDelay = TimeSpan.MinValue;
Task maxDelayTask = null;
foreach (var task in Tasks)
{
var delayedBy = task.DelayedBy();
if (maxDelay < delayedBy && delayedBy > TimeSpan.Zero)
{
maxDelay = delayedBy;
maxDelayTask = task;
}
}
if (maxDelayTask != null)
{
maxDelayTask.LastExecuted = DateTime.UtcNow;
maxDelayTask.Action();
}
}
}
线程大部分时间都在休眠,但它确实每 1 秒醒来一次以检查任务是否到期。这个 1 秒的间隔对于 15 分钟这样的间隔来说可能太短了,所以将它减少到 30 秒左右(这将是 SubsequentInterval
)。
希望有用!
关于c# - 在 C# 4.0 中具有持续运行线程的 Windows 服务的最佳解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4638261/
如果我错了,但身份验证 session 有 30 天的最大限制,请纠正我?如果是这种情况,有没有办法让我的服务器节点应用程序永远监听经过身份验证的 dataRef? 干杯, 旅行。 最佳答案 自 on
我目前正在阅读 book Continuos Delivery由 Humble/Farley 撰写,虽然里面的很多东西都是有道理的,但有一件事让我烦恼: 似乎作者只针对基于服务器的(单客户端?)应用程
好吧,我非常了解每个人对自制密码管理器的看法,但我希望得到帮助。 不用于实际使用,仅供学习。 我想知道,在 C++ 中如何拥有长期变量。或者真的,有什么长期的。 长期是什么意思?在下次运行 .exe
我在文本文件中有以下三行(最后 3 行): } } } 我想做的是做这样的事情: } } blablabla blablabla blabla
在 iOS 中,有没有一种简单的方法可以在每天的同一时间发送 10 天的推送通知?我不想向所有用户发送推送通知。我的应用程序的工作方式是,用户可以选择连续十天推送通知的时间。您有推荐的 API 吗?或
我正在努力寻找一种当前最先进的方法来处理频繁更新的通知(例如每 3 分钟一次)。似乎在较新的 Android 版本中内置了如此多的电源效率调整(幸运的是!),我之前成功使用的方法(使用 Broadca
我不得不在一些糟糕的房地产网站上花费大量时间。我比较精通 CSS,并且可以(在 FireFox 中)“检查元素”并更改 CSS 以隐藏或缩小特定页面的华而不实的元素。但我想将此自定义 CSS 应用于特
目前正在研究如何使用 signalR 在处理文件时向用户呈现文件的进度报告。我正在使用 asp.net MVC 4。通过 Ajax 进行发布/获取时,我可以轻松获取状态更改。 因为我需要上传一个文件(
这个问题在这里已经有了答案: How can I round up the time to the nearest X minutes? (15 个答案) Is there a simple fun
我有一个 php 脚本,我想运行特定的时间(例如 5 分钟),但只能运行一次。对于 cron 作业,这将无限期地运行。还有别的办法吗? 最佳答案 处理这个问题的方法是: 当某些事件触发需要 cron
我弄乱了我的 apache 和 php.ini 文件,我网站的用户仍然提示该网站在很短的时间后或每次他们关闭并打开同一个浏览器时将他们注销。 我正在运行 Apache 和 PHP。 我应该进行哪些设置
如何查询今天的总和需要减去前一天的总和,每天持续一个月。 SELECT COUNT(DISTINCT member_profile.memberProfileNumber) FROM member_p
这个问题在这里已经有了答案: How do I add a delay in a JavaScript loop? (32 个答案) 关闭 8 年前。 我认为这个问题之前一定有人问过,但我找不到其他
用户在我的网站上注册后,我们会向他发送一封确认电子邮件。我想要的是 - 三天内每 24 小时为用户重新发送一次电子邮件。例如: user_table id , name, date_registere
最近我从 Codeigniter 换到了 Laravel,一切都很顺利,除了我遇到了 Session::flash 的问题。 当我创建新用户时,我收到成功消息,但它会持续 2 个请求,即使我没有通过验
如果有人能帮助我解决这个问题,我将非常感激。 我正在尝试针对 CPU 使用率 >= 80% 持续 30 分钟或更长时间创建 Azure 监视器警报 我已附上警报规则条件的屏幕截图。在“评估依据”下,聚
如果有人能帮助我解决这个问题,我将非常感激。 我正在尝试针对 CPU 使用率 >= 80% 持续 30 分钟或更长时间创建 Azure 监视器警报 我已附上警报规则条件的屏幕截图。在“评估依据”下,聚
希望大家平安 1。我的目标 我正在尝试模拟 3 天的真实情况。系统每天只能工作 8 小时。 我的目标是模型运行 8 小时,持续 3 天,以获得足够的数据进行分析。 2。我的问题 我有一个代理预约时间表
我需要在 8 小时内每 5 分钟调用一次函数。问题是它必须是同一天。例如,如果用户在 3/29 晚上 11:59 登录系统,而现在是 3/30 凌晨 12:01,则不应再调用该函数。 我知道如何每
我正在开发一个 React Native 应用程序,该应用程序使用 Firebase 的 Firestore 作为后端。现在,每次收到新消息时,我都会从 Firestore 获取所有消息并更新我的状态
我是一名优秀的程序员,十分优秀!