用 Scrapy 做好的爬虫使用 Scrapyd 来管理发布启动等工作,每次手动执行也很繁琐;考虑可以使用 Hangfire 集成在 web 工程里。

Scrapyd 中启动爬虫的请求如下:

curl http://172.0.0.1:8081/schedule.json -d project=spider  -d spider=jrj_spider -u name:pwd
{"node_name": "iZbp1gf15gbzzqwvxbj18jZ", "status": "ok", "project": "spider", "spiders": 1, "version": "1492884063"}

修改:

        /// <summary>
/// 执行方法
/// </summary>
public async Task SchedulePollingBackgroundJob()
{
try
{
var response = await @"http://172.0.0.1:8081/schedule.json"
.WithBasicAuth("name", "pwd")
.PostUrlEncodedAsync(new { project = "spider", spider = "jrj_spider" })
.ReceiveString();
}
catch (Exception)
{
}
}

整个过程还是比较简单的,完整的代码:

/// <summary>
/// 配置接口
/// </summary>
public IConfigurationRoot Configuration { get; } /// <summary>
/// Redis 服务
/// </summary>
public static ConnectionMultiplexer Redis; /// <summary>
/// 构造方法
/// </summary>
/// <param name="env"></param>
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Redis = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("Redis"));
} // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//自定义的配置
services.Configure<DbSetting>(Configuration.GetSection("ConnectionStrings")); //注入 Hangfire服务
services.AddHangfire(config => config.UseRedisStorage(Redis));
// services.AddHangfire(config => config.UseSqlServerStorage("<connection string>")); //添加 cookie 中间件
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}) //.AddAzureAdB2C(opts => Configuration.Bind("AzureAdB2C", opts))
.AddCookie(opts =>
{
opts.LoginPath = new PathString("/account/login");
opts.AccessDeniedPath = new PathString("/account/denied");
});
//返回大小写问题
services.AddMvc()
.AddJsonOptions(option => option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles(); //添加验证中间件
app.UseAuthentication(); //Hangfire
//http://docs.hangfire.io/en/latest/configuration/using-dashboard.html#configuring-authorization
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[] { new HangfireDashboardAuthorizationFilter() }
});
app.UseHangfireServer();
app.UseHangfireDashboard(); //http://cron.qqe2.com
//0 0 * * MON-FRI At 00:00, Monday through Friday
//Cron.Daily(16, 30) 30 16 * * *
//30 16,17,18 * * *
//30 16,17,18 * * MON-FRI
//https://github.com/HangfireIO/Cronos
RecurringJob.AddOrUpdate(() => SchedulePollingBackgroundJob(), @"30 16,17,18 * * *", TimeZoneInfo.Local);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Hq}/{action=Index}/{id?}");
});
}

Attention: If you are using Microsoft.Extensions.Caching.Redis package, you will need to use Hangfire.Redis.StackExchange.StrongName instead, because the former package requires StackExchange.Redis.StrongName instead of StackExchange.Redis!

REFER:

https://github.com/marcoCasamento/Hangfire.Redis.StackExchange

ASP.NET Core 中使用 Hangfire 定时启动 Scrapyd 爬虫的更多相关文章

  1. ASP.NET Core 中的应用程序启动 Startup

      ASP.NET Core 应用使用Startup类来作为启动类.   Startup类中包含了ConfigureServices方法,Configure方法,IConfiguration,IHos ...

  2. Hangfire在ASP.NET CORE中的简单实现

    hangfire是执行后台任务的利器,具体请看官网介绍:https://www.hangfire.io/ 新建一个asp.net core mvc 项目 引入nuget包 Hangfire.AspNe ...

  3. Hangfire在ASP.NET CORE中的简单实现方法

    hangfire是执行后台任务的利器,具体请看官网介绍:https://www.hangfire.io/ 新建一个asp.net core mvc 项目 引入nuget包 Hangfire.AspNe ...

  4. ASP.NET Core 中文文档 第三章 原理(1)应用程序启动

    原文:Application Startup 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:谢炀(kiler398).许登洋(Seay) ASP.NET Core 为你的应用程 ...

  5. [08]ASP.NET Core 中 launchsettings.json 启动配置文件

    ASP.NET Core launchsettings.json 启动配置文件 本文作者:梁桐铭- 微软最有价值专家(Microsoft MVP) 文章会随着版本进行更新,关注我获取最新版本 本文出自 ...

  6. 探索ASP.Net Core 3.0系列六:ASP.NET Core 3.0新特性启动信息中的结构化日志

    前言:在本文中,我将聊聊在ASP.NET Core 3.0中细小的变化——启动时记录消息的方式进行小的更改. 现在,ASP.NET Core不再将消息直接记录到控制台,而是正确使用了logging 基 ...

  7. Core中使用Hangfire

    之前使用Quartz.Net,后来发现hangfire对Core的继承更加的好,而且自带管理后台,这就比前者好用太多了. 安装注册 安装 PM> Install-Package Hangfire ...

  8. 在 ASP.NET Core 中执行租户服务

    在 ASP.NET Core 中执行租户服务 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://gunna ...

  9. ASP.NET Core中的OWASP Top 10 十大风险-失效的访问控制与Session管理

    不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: https://dotnetcoretutorials.com/201 ...

随机推荐

  1. 振动器(Vibrator)

    package com.wwj.serviceandboardcast;   import android.app.Activity; import android.app.Service; impo ...

  2. DOS的几个常用命令

    1.rem:注释 DOS中的注释,其后面的内容会被自动忽略.双冒号(::)也有相同的效果 相当于R语言和Python中的# 2.set:设置变量 set var = 1 将1赋值给变量var 打印出来 ...

  3. 移动端meta设置

    网页作者: <meta name="author" content="name, email@gmail.com"/>声明文档使用的字符编码: &l ...

  4. 20145232 韩文浩 《Java程序设计》第4周学习总结

    教材学习内容总结 · Chapter 继承与多态 继承:避免多个类间重复定义共同行为.继承可以理解为一个对象从另一个对象获取属性的过程. 所有Java的类均是由java.lang.Object类继承而 ...

  5. linux 环境安装及学习

    一.Httpd Linux(Apache)Httpd服务器安装,启动及httpd.conf配置详解   https://blog.51cto.com/itwish/2160492 httpd-2.4. ...

  6. jQuery如何获取元素及选择器的参考

    获取元素 Jquery当中几乎所有的功能.选择.事件处理等都用到了这个函数.通常用来获取元素,获取到的元素都会被存储为jQuery对象. 例如: 先设定一个id为aaa的div <body> ...

  7. java基础-day14

    第01天 java面向对象 今日内容介绍 u 接口 u 匿名对象&final u 多态 第1章   接口 1.1  接口的概述 接口是功能的集合,同样可看做是一种数据类型,是比抽象类更为抽象的 ...

  8. Codeforces791A Bear and Big Brother

    A. Bear and Big Brother time limit per test 1 second memory limit per test 256 megabytes input stand ...

  9. js获取元素下标

    <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title> ...

  10. bootstrap 警告框多个删除

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...