用 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. 微信小程序之基础入门

    微信小程序有几个基础的文件:js(JavaScript逻辑代码),json(页面配置),wxml(类似hthml布局),wxss(css样式) 我们使用app.json文件来对微信小程序进行全局配置, ...

  2. 【慕课网实战】Spark Streaming实时流处理项目实战笔记十之铭文升级版

    铭文一级: 第八章:Spark Streaming进阶与案例实战 updateStateByKey算子需求:统计到目前为止累积出现的单词的个数(需要保持住以前的状态) java.lang.Illega ...

  3. 踏破铁鞋无觅处,从AsyncTask学Android线程池

    android对于主线程的响应时间限制的非常严格,稍有不慎就会遇到Application Not Responding(ANR)的弹框.用户可以轻点手指关掉你的APP.官方文档写的非常明确!同时,保持 ...

  4. 批量插入,批量修改的sql

    sql 1  批量插入 <insert id="batchInsert" useGeneratedKeys="true" parameterType=&q ...

  5. c语言:辗转相除法求最大公约数、最小公倍数

    辗转相除法,又称欧几里得算法.两个正整数a和b(a>b),它们的最大公约数等于余数c和较小的数b之间的最大公约数.最小公倍数=两数之积/最大公约数 #include <stdio.h> ...

  6. [ 9.12 ]CF每日一题系列—— 960B暴力数组

    Description: 给你两个数组,顺序一定,问你第一个数组连续的几个值等于下一个数组连续的几个值,然后寻找这个值得最大值,也就是满足就换 Solution: 用两个变量索引,判断即可 #incl ...

  7. linux 三剑客之awk

    #AWK命令 基础显示 打印install.log文件中包含data字段行的第二区域 awk '/data/ {print $2}' install.log 查看num10.txt的第一行 head ...

  8. rsync+sersync+inotify实现服务器间文件同步之一

    rsync+sersync+inotify实现服务器间文件同步之一:rsync安装配置 2013年12月14日 ⁄ Linux管理, 服务器集群技术 ⁄ 共 4925字 ⁄ rsync+sersync ...

  9. vsm安装

    一. 部署环境介绍 软件需求 1) CentOS 6.5 64bit 2) Ceph 0.80.6 网络拓扑介绍 1) Controller Node 由Console节点组成,安装VSM控制平台 2 ...

  10. ClientDataSet 心得

    1.   与TTable.TQuery一样,TClientDataSet也是从TDataSet继承下来的,它通常用于多层体系结构的客户端.很多数据库应用程序都用了BDE,BDE往往给发布带来很大的不便 ...