I have a cron task placed under myProject/lib/task. This cron works daily for over a year.
However now I have to create a button inside my project to do the same process as the cron whenever my client needs. The code is too complex and I can't rewrite everything on a normal action.
Is there a way to call a cron task from a normal action?
Here's how you can call a task from an action, you just need to add a link to it and you'll be good. I've used the standard Symfony 'Clear Cache' task in the example, but you can change it to yours:
public function executeRunTaskTest(sfWebRequest $request)
{
// need to be working in the project root
chdir(sfConfig::get('sf_root_dir'));
// init the task we want to run
$task = new sfCacheClearTask($this->dispatcher, new sfFormatter());
// run the task
$task->run(
array(), // array of arguments
array(
'app' => 'frontend',
'env' => 'prod',
'type' => 'all',
) // array of options
);
// back to where we came from
$this->redirect($request->getReferer());
}
You could also use the PHP exec() or shell_exec() functions, but this Symfony solution is probably easier. :)
Related
Does anyone know if it's possible to make a Heroku Scheduler job that would send an email to all of my users once per day? I'm using Meteor and MongoDB.
I can see that the Heroku Scheduler can run a command such as "node somefile.js" but I can't seem to figure out how to make a connection to the mongodb in a file like this. Can I somehow tap into the DB without involving Meteor in this?
Any help would be appreciated!
I eventually found a package to do so: synced-cron. Basically, you need to setup a method in which use the package to fire a recurring job.
The package website also has a sample code:
SyncedCron.add({
name: 'Crunch some important numbers for the marketing department',
schedule: function(parser) {
// parser is a later.parse object
return parser.text('every 2 hours');
},
job: function() {
var numbersCrunched = CrushSomeNumbers();
return numbersCrunched;
}
});
Here you just need to replace the code in the job function to send out the email.
The job supports schedules like "every 5 minutes", "at 5:00pm", etc. The package relies on the text parser in Later.js to parse the schedule. You can refer to the Later.js doc.
Two different options.
The first is to use Heroku's scheduler,
In which you create a text file in your bin directory:
#! /app/.heroku/node/bin/node
var test = require('./jobToDo') //put your job in this file (jobToDo.js)
Now you don't have to put the job in another .js file, but it makes it easier to work with, rather than coding in a plain text file. (put again that is up to you)
The first line #! /app/.heroku/node/bin/node may be different for you depending on how your configuration is set up, depending on your OS and node/npm set up.
The second option is a cron style library. This will allow you to decide when you want your code to run.
This is pretty easy, and for me the preferred method.
var CronJob = require('cron').CronJob;
var fn = function(){
// Do Something
}
var job = new CronJob({
cronTime: "00 00 02 * * 1-5",
onTick: fn,
start: true,
timeZone: 'America/Los_Angeles'
});
You can look at documentation on github
I am not very much familiar with nodejs but, I need some guidance in my task. Any help would be appreciated.
I have nodejs file which runs from command line.
filename arguments and that do some operation whatever arguments I have passed.
Now, I have html page and different options to select different operation. Based on selection, I can pass my parameters to any file. that can be any local node js file which calls my another nodejs file internally. Is that possible ? I am not sure about what would be my approach !
I always have to run different command from terminal to execute different task. so, my goal is to reduce that overhead. I can select options from UI and do operations through nodejs file.
I was bored so I decided to try to answer this even though I'm not totally sure it's what you're asking. If you mean you just need to run a node script from a node web app and you normally run that script from the terminal, just require your script and run it programmatically.
Let's pretend this script you run looks like this:
// myscript.js
var task = process.argv[2];
if (!task) {
console.log('Please provide a task.');
return;
}
switch (task.toLowerCase()) {
case 'task1':
console.log('Performed Task 1');
break;
case 'task2':
console.log('Performed Task 2');
break;
default:
console.log('Unrecognized task.');
break;
}
With that you'd normally do something like:
$ node myscript task1
Instead you could modify the script to look like this:
// Define our task logic as functions attached to exports.
// This allows our script to be required by other node apps.
exports.task1 = function () {
console.log('Performed Task 1');
};
exports.task2 = function () {
console.log('Performed Task 2');
};
// If process.argv has more than 2 items then we know
// this is running from the terminal and the third item
// is the task we want to run :)
if (process.argv.length > 2) {
var task = process.argv[2];
if (!task) {
console.error('Please provide a task.');
return;
}
// Check the 3rd command line argument. If it matches a
// task name, invoke the related task function.
if (exports.hasOwnProperty(task)) {
exports[task]();
} else {
console.error('Unrecognized task.');
}
}
Now you can run it from the terminal the same way:
$ node myscript task1
Or you can require it from an application, including a web application:
// app.js
var taskScript = require('./myscript.js');
taskScript.task1();
taskScript.task2();
Click the animated gif for a larger smoother version. Just remember that if a user invokes your task script from your web app via a button or something, the script will be running on the web server and not the user's local machine. That should be obvious but I thought I'd remind you anyway :)
EDIT
I already did the video so I'm not going to redo it, but I just discovered module.parent. The parent property is only populated if your script was loaded from another script via require. This is a better way to test if your script is being run directly from the terminal or not. The way I did it might have problems if you pass an argument in when you start your app.js file, such as --debug. It would try to run a task called "--debug" and then print out "Unrecognized task." to the console when you start your app.
I suggest changing this:
if (process.argv.length > 2) {
To this:
if (!module.parent) {
Reference: Can I know, in node.js, if my script is being run directly or being loaded by another script?
Can anyone tell me how to setup a cronjob in TYPO3? I've created a TYPO3 extension which I want to run once a week. I've already installed the scheduler extension, but it only allows some extensions (e.g., tt_news ) to be executed.
Thank you.
your extension must support the Scheduler - system extension (maybe you'll need to install it first). Therefore you have to register your extension in the Scheduler Service.
via your ext_localconf.php
if (!defined ('TYPO3_MODE')) die ('Access denied.');
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks']['TX_YOUR_EXTENSIONKEY'] = array(
'extension' => $_EXTKEY,
'title' => 'Some meningful Title',
'description' => 'Some Discription of the Task'
);
you need to create the file tasks/class.TX_YOUREXTENSKEY.php in your extension directory
class TX_YOUREXTENSKEY extends tx_scheduler_Task {
public function execute() {}
...
}
the execute function is called if the task gets executed. it should return true if everything went fine and false if you got some error.
at last your class needs to be loaded this can be done using ext_autoload.php (in your extension root, see TYPO3 Wiki: Autoload for more details)
<?php
return array(
'tx_sfpinger_pinger' => t3lib_extMgm::extPath('sfpinger', 'tasks/class.tx_sfpinger_pinger.php')
);
?>
Finally you need to add to your system cron command that will be running Scheduler ext periodically (you'll find it on the Scheduler's Setup check section) and also add your created task to the its tasks list.
You can check a demo task which is just a sample from which you can copy code and paste in your extension.
Also check documentation delivered with scheduler task in folder on your TYPO3 implementation: /typo3/sysext/scheduler/doc/manual.sxw
I'm trying to implement a cron job in my wordpress blog. I want to do this stuff in a plugin, for testing I'm trying to write in one file some log information every 10 minutes, for do that I wrote this code (PHP):
add_filter( 'cron_schedules', 'ten_minute_prefix' );
function ten_minute_prefix( $schedules )
{
$schedules['tenmins'] = array(
'interval' => 600,
'display' => __( '10 minutes' ),
);
return $schedules;
}
//This must be here always
add_action('my_task_hook', 'foo_task');
function foo_task()
{
file_put_contents('data.txt', date("Y-m-d H:i:s") . "task do it\r\n", FILE_APPEND);
}
//This is executing in my plugin page in tools section
function myplugin()
{
//For checking permissions
file_put_contents('data.txt', date("Y-m-d H:i:s") . "Task begin\r\n", FILE_APPEND);
wp_schedule_event( time(), 'tenmins', 'my_task_hook' ); // hourly, daily and twicedaily
echo "SCHEDULE ACTION";
...
}
For checking that i have created really the cron job, i using for example this plugin http://wordpress.org/extend/plugins/cron-view/. This plugin says me this "Entry #10: my_task_hook √ action exists".
But nothing is happening, the file is not written, what is the problem?
Edit:
I have added one line in myplugin function for see if i have permission for writing files. In fact, i have got permissions, a data.txt file is created in wp-admin/ folder.
Edit2:
I just to understand the cron jobs in wordpress!
Cron in wordpress is not a real cron, it only fires when any user opens the webpage, if no one opens the page, the process won't fire. So, if a blog has not visitors, cron jobs dont work.
Please, correct me if i am in a mistake.
It could be because you don't have write permissions to write to the folder where data.txt is in. As you haven't explicitly defined which folder to write to, it will write to the folder your PHP file is in.
1) right. check is your directory writable...
if (is_writable(dirname(__FILE__))){
file_put_contents(dirname(__FILE__).'/data.txt', date("Y-m-d H:i:s") . "task do it\r\n", FILE_APPEND);
} else {
mail('yourmail#example.com', 'oops!', 'error writing');
}
2) where is your cron scheldule activated?
add_action('activate_' . __FILE__, 'plugin_activate_demo'));
add_action('deactivate_' .__FILE__, 'plugin_deactivate_demo'));
function plugin_activate_demo(){
wp_schedule_event( time(), 'tenmins', 'my_task_hook' );
}
function plugin_deactivate_demo(){
wp_clear_scheduled_hook('my_task_hook' );
}
3) almost imposible situation which i got on work - Check do you have working cron... simple by adding mail or something like that to your hook_action code. on some servers due dns problems (many networked servers and url routes issue) server name not responding while http://yourservername.com requested (by wp-cron).
I have a safecracker form that submits an entry. The form consists of title, url_title, and description. I want to create an extension hook that filters out certain words if they exist in the title of the entry.
I already have a function that take care of the cleaning function clean(){....}. I understand that we need to use an extension hook so we can clean the title upon saving the entry.
What extension hook do i need to use for that. can you give me a complete example of an extension hook. I'm very good with PHP but still new to hooks and how they should be implemented. I already read the EE documentation but still find some confusion of how a hook is used
First head over to http://pkg.io/ and get your base extension file.
You'll probably want to use the 'safecracker_submit_entry_start' hook to throw an error if unclean word is entered. The most important part of the extension is registering the method and hook you want to use, otherwise none of the code will run.
Your code should look something like this:
public function activate_extension()
{
// Setup custom settings in this array.
$this->settings = array();
$data = array(
'class' => __CLASS__,
'method' => 'clean', // point to the method that should run
'hook' => 'safecracker_submit_entry_end', // point to the hook you want to use to trigger the above method.
'settings' => serialize($this->settings),
'version' => $this->version,
'enabled' => 'y'
);
$this->EE->db->insert('extensions', $data);
}
Once the method has been called you can start your cleaning. Make sure you pass the safecracker object to your clean method when defining it. For example:
public function clean($sc){
print_r($sc);
}