简体   繁体   English

如何自动每小时运行一次CasperJS脚本?

[英]How to run a CasperJS script every hour automatically?

I have a CasperJS code that executes some tasks on my website. 我有一个CasperJS代码,可以在我的网站上执行一些任务。 I want the code to run every hour! 我希望代码每小时运行一次!

For the moment being, the code is running locally and manually (using casperjs cas.js ) every time. 目前,代码每次都在本地手动运行(使用casperjs cas.js )。 Now I want: 现在我要:

  1. To make it run every hour automatically 使它每小时自动运行
  2. To deploy it somewhere (eg Heroku) 部署到某个地方(例如Heroku)

I could achieve the first objective by making a Node server that runs the command casperjs casper/cas.js every hour (using setInterval function). 通过使节点服务器每小时运行一次casperjs casper/cas.js命令(使用setInterval函数),可以实现第一个目标。 However, I couldn't deploy it on Heroku since it supports only one type of code (Node.js). 但是,我无法在Heroku上部署它,因为它仅支持一种类型的代码(Node.js)。 The cas.js script is written with CasperJS, so it couldn't been executed! cas.js脚本是用CasperJS编写的,因此无法执行!

What is the best way to achieve these two goals? 实现这两个目标的最佳方法是什么?

Let's assume you are on Linux... 假设您使用的是Linux ...


1. The most elegant solution is to use a cron job , as suggested by Vaviloff . 1.最优雅的解决方案是使用 Varonoff建议的cron作业

If you want to execute your CasperJS script every hour, you can edit your crontab with crontab -e and then add the following entry: 如果要每小时执行一次CasperJS脚本,则可以使用crontab -e编辑crontab,然后添加以下条目:

0 * * * * PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs /usr/local/bin/casperjs /absolute/path/to/your/casper/script.js 2>&1

Some remarks: 一些说明:

  • 0 means "0 minute". 0表示“ 0分钟”。 It is required here, otherwise your script will run every minute. 这是必需的,否则您的脚本将每分钟运行一次。
  • Since CasperJS depends on PhantomJS , you have to specify the path to the PhantomJS command using the proper environment variable ( PHANTOMJS_EXECUTABLE ). 由于CasperJS依赖于PhantomJS ,因此您必须使用适当的环境变量( PHANTOMJS_EXECUTABLE )指定PhantomJS命令的路径。
  • Make sure PhantomJS & CasperJS paths are /usr/local/bin/phantomjs and /usr/local/bin/casperjs respectively, using which ( which phantomjs & which casperjs ). 确保PhantomJS和CasperJS路径分别是/usr/local/bin/phantomjs/usr/local/bin/casperjs ,使用whichwhich phantomjswhich casperjs )。
  • Do not forget to write the absolute path to your own CasperJS script. 不要忘记为您自己的CasperJS脚本编写绝对路径
  • 2>&1 redirects stderr to stdout . 2>&1stderr重定向到stdout


2. Use SpookyJS if you want to run CasperJS scripts with Node.js. 2.如果要通过Node.js运行CasperJS脚本,请使用SpookyJS

npm i spooky

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM