Setting up a cron Job - cron

Please I am new to cron jobs and only heard of it recently.
The thing is I am trying to send a message to myself via a phpscript.
I need the cron job to read the php cript and send the appropriate message.
here is the php self mailer I have in place.
<?php
$recipient = "*******#gmail.com";
$subject = "Flight Status";
$body = "Flight has just landed.";
if(mail($recipient, $subject, $body))
{
echo("<p>Message successfully sent</p>");
}
else
{
echo("<p>Message Delivery failed </p>");
}
?>

you can read the manual for cron with man 5 crontab. It contain example as well.
for example,
# run at 2:15pm on the first of every month -- output mailed to paul
15 14 1 * * $HOME/bin/flight.php

Sending email through phone is complicated, as you need a smtp server set up. A better solution would be to send yourself a message via a chat application.
I personally use nimrod for this : https://www.nimrod-messenger.io
It's messenger only but other chat systems are planned.

Related

NodeJS | Python | Heroku - Scheduling Emails 48 Hours after form Post

I've made a PWA with ReactJS + NodeJS, running with a python backend that's being spawned as a child process by the Node server, I have to send and generate a document generated by python via email 48 hours after payment verification is called, how do I accomplish this? My current method includes :
def sendInTwoDays(recipient, filename):
time = round(random.uniform(0.8, 2.0), 2)
time = round(time * 24 * 3600, 2)
time /= 10000 #for testing
print("[python:sendInTwoDays()] > Sleep ({} seconds) : {} days".format(time, time/3600))
sleep(time)
sendNow(recipient, filename)
I hate it since it uses "sleep()" and sleep on a webserver just doesn't sit right with me.
Please suggest a better way to accomplish the same on heroku.
I would suggest a scheduling(cron) approach with Heroku Scheduler like to check due emails every fifteen minutes. Rather than letting the process sit for 48 hours, I would save the email data along with the emailing time in the database and let the scheduler can invoke an API/task to call the Python script to output and email documents which are due after 48 hours.
The emails will not be sent out after exact 48 hours, but should be close.

Clear "pending_update_count" in Telegram Bot

I want to clear all pending_update_count in my bot!
The output of below command :
https://api.telegram.org/botxxxxxxxxxxxxxxxx/getWebhookInfo
Obviously I replaced the real API token with xxx
is this :
{
"ok":true,"result":
{
"url":"",
"has_custom_certificate":false,
"pending_update_count":5154
}
}
As you can see, I have 5154 unread updates til now!! ( I'm pretty sure this pending updates are errors! Because no one uses this Bot! It's just a test Bot)
By the way, this pending_update_count number are increasing so fast!
Now that I'm writing this post the number increased 51 and reached to 5205 !
I just want to clear this pending updates.
I'm pretty sure this Bot have been stuck in an infinite loop!
Is there any way to get rid of it?
P.S:
I also cleared the webhook url. But nothing changed!
UPDATE:
The output of getWebhookInfo is this :
{
"ok":true,
"result":{
"url":"https://somewhere.com/telegram/webhook",
"has_custom_certificate":false,
"pending_update_count":23,
"last_error_date":1482910173,
"last_error_message":"Wrong response from the webhook: 500 Internal Server Error",
"max_connections":40
}
}
Why I get Wrong response from the webhook: 500 Internal Server Error ?
I think you have two options:
set webhook that do nothing, just say 200 OK to telegram's servers. Telegram wiil send all updates to this url and the queque will be cleared.
disable webhook and after it get updates by using getUpdates method, after it, turn on webhook again
Update:
Problem with webhook on your side. You can try to emulate telegram's POST query on your URL.
It can be something like this:
{"message_id":1,"from":{"id":1,"first_name":"FirstName","last_name":"LastName","username":"username"},"chat":{"id":1,"first_name":"FirstName","last_name":"LastName","username":"username","type":"private"},"date":1460957457,"text":"test message"}
You can send this text as a POST query body with PostMan for example, and after it try to debug your backend.
For anyone looking at this in 2020 and beyond, the Telegram API now supports clearing the pending messages via a drop_pending_updates parameter in both setWebhook and deleteWebhook, as per the API documentation.
Just add return 1; at the end of your hook method.
Update:
Commonly this happens because of queries delay with the database.
I solved is like this
POST tg.api/bottoken/setWebhook to emtpy "url"
POST tg.api/bottoken/getUpdates
POST tg.api/bottoken/getUpdates with "offset" last update_id appeared before
doing this serveral times
POST tg.api/bottoken/getWebhookInfo
had a look if all away.
POST tg.api/bottoken/setWebhook with filled "url"
If you are using webhook, you can follow these steps
On your web browser, enter the following url with your right value of bot
https://api.telegram.org/bot/getWebhookInf
You will get a result like this on your screen
{"ok":true,"result":{"url":"url_value",...}}
On the displayed result, copy the entire url_value without quotes and replace it on this second url
https://api.telegram.org/bot/setWebhook?url=url_value&drop_pending_updates=True
Enter the second url with right bot and url_value in your web browser then press ENTER
Done!
i solve it by Change file access permissions file - set permissions file to 755
and second increase memory limit in php.ini file
A quick&dirty way is to get a temporary webhook here: https://webhook.site/ and
set your webhook to that (it will answer with a HTTP/200 code everytime, reseting your pending messages to zero)
I faced the same issue for my tele bot after user edited existing message. My bot receives update with editedMessage continuously, but update.hasMessage() was empty. As a result number of updates rocketly increased and my bot stack.
I solved this issue by adding handling for use case when message is missing - send 200 code:
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {
update = MAPPER.readValue(event.getBody(), Update.class);
if (!update.hasMessage()) {
return new APIGatewayProxyResponseEvent()
.withStatusCode(200) // -> !!!!!! return code 200
.withBody("message is missing")
.withIsBase64Encoded(false);
}
... ... ...

Setup Heroku Scheduler job to email all users (Meteor/MongoDB)

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

Login plugin Hooks not running

I am trying to send a 2nd email to my sites admin when a user registers.
I made a postHook snippet that sends an email but it didnt work - the Registration process worked as expected, but I got no 2nd email from the hook.
In testing I set the hook from postHook to preHook and tried again - this time the form didnt process at all - no new user was created and no activation email was sent. It didnt even redirect to the submittedResourceId.
So, I deleted everything in my preHook Snippet, except the return true; and tried again - still nothing.
It appears Login wont run any Hooks at all. I have no idea why.
Would anyone be able to suggest any fixes?
My register snippet is:
[[!Register?
&submitVar=`registerbtn`
&activationResourceId=`19`
&activationEmailTpl=`lgnActivateEmailTpl`
&activationEmailSubject=`Thanks for Registering!`
&submittedResourceId=`23`
&usergroups=`2`
&validate=`nospam:blank,
username:required:minLength=^6^,
password:required:minLength=^6^,
password_confirm:password_confirm=^password^,
fullname:required,
email:required:email`
&preHooks=`adminEmailHook`
]]
I've done something similar before. There is my code:
[[!Register? &postHooks=`sendMessageToAdmin`
Snippet sendMessageToAdmin:
<?php
$message = 'Auto message:<br><br>A new user signed up: '.$hook->getValue('fullname') . ', using email address '.$hook->getValue('email').'.';
$modx->getService('mail', 'mail.modPHPMailer');
$modx->mail->set(modMail::MAIL_BODY,$message);
$modx->mail->set(modMail::MAIL_FROM,'info#domain.com');
$modx->mail->set(modMail::MAIL_FROM_NAME,'My website');
$modx->mail->set(modMail::MAIL_SENDER,'Auto message from my website');
$modx->mail->set(modMail::MAIL_SUBJECT,'Someone signed up');
$modx->mail->address('to','info#domain.com');
$modx->mail->setHTML(true);
if (!$modx->mail->send()) {
$modx->log(modX::LOG_LEVEL_ERROR,'sendMessageToAdmin: An error occurred while trying to send the email: '.$err);
}
$modx->mail->reset();
/* tell our snippet we're good and can continue */
return true;

How to use multi-threading in rails 3?

I am sending mail to the users using actionmailer through postmark. This is my code in controller:
#users = User.where(some condition)
#product = Product.find_by_name(some name).first
for user in #users
UserMailer.new_product_arrival(user, #product, home_url).deliver
end
and this my user_mailer.rb
def new_product_arrival(user,product,home_url)
#from = Settings.mailer_from_address
#recipients = user.login
#sent_on = Time.now
#user = user
#product = product
#content_type = "text/html"
#home_url = home_url
end
The problem is that if there are more than 10 users it takes a very long time because of the for loop. I need to know if we can handle this by using multi-threading or background job. I don't want to use background job, but can anyone tell me how to implement the above using multi-threading.
I am using ruby 1.8.7 and rails 3.0.7
There basically two ways to wrap your loop in order to get "multi-threading":
Spwan a thread for each delivery and join them back to the main thread
threads = []
for user in #users
threads << Thread.new do
UserMailer.new_product_arrival(user, #product, home_url).deliver
end
end
threads.each(&:join)
fork over the entire rails app ( pretty messy but the rails app serving the request will respond immediately ) and have the process detached:
process = fork do
for user in #users
UserMailer.new_product_arrival(user, #product, home_url).deliver
end
Process.kill("HUP")
#sends the kill signal to current Process, which is the Rails App sending your emails
end
Process.detach(process)
Hope that helps
our developer Artem recently made a major update to the Postmark gem
which allows you to send emails easily in batches, which should allow you to send emails faster. Check it out.
Try delayed_job gem. This is a database-based background job gem. We used it in an e-commerce website, for example, sending order confirmation emails to users.
These tasks can happen asynchronously in the background, because your Rails app doesn't need
them executed immediately.
um im a rails student from nairobi dev school kenya ..and i think you can give this a try ,..soo what you are having there is the delayed response due to the number of users ..you can try long polling an example
poll = function (){
s.ajax{
url:/'chat.json'
data: { last_time: get last_time () }
}}.done(function(data) {
// handle data
setTimeout(poll,1000);
});
}
try that in your ow way ..this is useful for a real time application..o you can use even action controller:: live ..i think youre farmiliar with threading with rails .also .the above exmples will hep you ,,hopefuly
\

Resources