Creating a scheduled task to "ping"/"poke" a URL via a batch file

时间:2015-11-12 11:41:01

标签: batch-file cmd scheduled-tasks windows-server-2008 wsh

What I want to do

I want to daily ping/poke a URL to activate a action I have written in C#, and is running on a webserver. To do this I expected that I could use the task scheduler.

My setup

I have set up the scheduled tasks action to call this program:

C:\...\_resources\callurl.cmd"

Created from this code taken from this SO post

@if (@This==@IsBatch) @then
@echo off
rem **** batch zone *********************************************************

    setlocal enableextensions disabledelayedexpansion

    rem Batch file will delegate all the work to the script engine 
    if not "%~1"=="" (
        wscript //E:JScript "%~dpnx0" %1
    )

    rem End of batch area. Ensure batch ends execution before reaching
    rem javascript zone
    exit /b

@end
// **** Javascript zone *****************************************************
// Instantiate the needed component to make url queries
var http = WScript.CreateObject('Msxml2.XMLHTTP.6.0');

// Retrieve the url parameter
var url = WScript.Arguments.Item(0)

    // Make the request

    http.open("POST", url, false);
    http.send();

    // All done. Exit
    WScript.Quit(0);

I then add the following argument to the task

/c "http://localhost/Controller/ActionToInvoke?guid=SOME-GUID"

The idea to use "/c" I have from this question.

The useraccount used to run the task is SYSTEM

When I do this nothing happens. Sometimes i CMD windows pops up for a split second, sometimes nothing happens. In both cases I can't see my action being hit (debugging the application and have set a breakpoint at the entry point)

Running it in CMD

If I open up my command promt, and run the command like this

callurl.cmd "http://localhost/Controller/ActionToInvoke?guid=SOME-GUID"

there is no problem. Here callurl.cmd does what I expect it to do, it calls my action.

What can I be doing wrong? Is there something here that I don't see?

1 个答案:

答案 0 :(得分:2)

我强烈建议通过Powershell来做这件事。它使用调度程序更容易,更完美。以下是调用/触发URL的代码:

$url="http://localhost/Controller/ActionToInvoke?guid=SOME-GUID"
(New-Object System.Net.WebClient).DownloadString("$url");

将此代码保存在* .ps1文件中并创建执行它的任务。就是这样。没有批处理,没有Java- / VBScript等等。只是纯粹的Powershell。

如果您不允许在您的计算机上执行ps脚本,那么这就是您执行此操作的方法:

  1. 以管理员身份打开Powershell
  2. 执行命令set-executionpolicy remotesigned
  3. 有不同的可行政策,而不是remotesigned。我甚至更喜欢unrestricted

    编辑:如果您希望能够将URL作为参数传递,则修改后的代码如下:

    param([String]$url="")
    (New-Object System.Net.WebClient).DownloadString("$url");
    

    使用filename.ps1 -url http://localhost/Controller/ActionToInvoke?guid=SOME-GUID调用该文件。

    您还可以转到任务计划程序,创建新任务,输入所有随机内容,转到"操作"将powershell输入"程序/脚本"字段和"C:\MyScript.ps1 -url http://localhost/Controller/ActionToInvoke?guid=SOME-GUID"进入"添加参数(可选)"字段。