I would like to create a feature for my web application that once a user is entered in my database, every 4 weeks an email is sent to them reminding them to, for example, give some feedback. I've heard cron job is what Im looking for but Im curious what else is out there, is there maybe a php script that exists or an easy way to do it?
I want something like a countdown from once they enter the database to start counting down till 4 weeks has passed then call a php file or something that sends an email of my choosing to them. if this is possible let me know! thank you
I would say to use a cron job (it could run everyday at a certain time that would be good to send an email), and the cron job could call a php script that would look through all your users and check when they signed up, and see if anyone signed up 4 weeks ago (or some multiple of that). For anyone who meets this condition, you could go through a loop and send them emails with the mail() function.
Cron Job
Log into a shell on your server and type "sudo crontab -e" and type in something like this:
30 14 * * * php path/to/some/phpscript.php
In this example, phpscript.php is going to be run at 14:30 every day (2:30 pm). But that doesn't mean it's going to email all the users every day! See the script below.
PHP Script
<?php
# get all users (or your query could choose only users who signed up (4 weeks)*n ago)
$result = mysql_query('SELECT * FROM user');
$users = array();
while($row = mysql_fetch_assoc($result)) $users[] = $row;
# loop through users and (if you didn't already check) see which ones have signed up (4 weeks)*n ago
foreach ($users as $user) {
# take the number of seconds and convert it to number of days
$today = (int)(strtotime(date('c')) / 60 / 60 / 24);
$signup_day = (int)(strtotime($user['signup_date']) / 60 / 60 / 24);
# check if the amount of days since signup is a multiple of 28 (4*7)
if (($today - $signup_day) && ($today - $signup_day) % 28 == 0) {
send_mail_to($user);
}
}
?>
Related
I'm programming my own "smart home" as a learning project.
My code is running fine. I'm looking for help to improve the efficiency and of the code and/or the setup of crontab + php code.
I'm monitoring the energy consumption of my washing machine with a WIFI energy meter. Target is to notify me once the washing machine is completed so I don't forget to clear it.
on my Pi I have a crontab like so:
*/20 7-22 * * * /usr/bin/php '/home/holger/html/plugs/washer.php'
which runs following php code (I simplified for better readability):
[...]/I call the function, of course, but this function does the main task
function loop($maschine, $watt_init, $trashhold){
$max = 75;//max loops to avoid endless runs
$i = 1;//start counter
$tackt = 3;//tact time to check energy consumption
//$trashhold = 4;//ab x Watt kein standby
if ($watt_init < 1 ) {//Machine is switched off if energy consumption < 1 Watt
die;//quit
}
elseif ($watt_init < 2 ) {//Machine is switched off or in standby if energy consumption < 1 Watt
die;//quit
}
else {//Any thing else: Machine is running
while ($i < $max) {//loop as long as max loops are not reached
$watt_current = json_combine(IPplug5);//getting current energy consumption from WIFI energy meter via JSON
sleep(60*$tackt);//sleep and continue every 60s x tact time
$i++;//increase counter +1
//compare actual consumption with defined trashhold
if ($watt_current[0] >= $trashhold) {//continue while energy consumption bigger then trashhold
continue;//repeat loop
}
elseif ($watt_current[0] < $trashhold) {//stop if energy consumption lower then trashhold
break;//stop loop
}
}
echo "Program done. please clear. Runtime: " . $i*$tackt. "Min."
//[...] message me to my telegram bot
}
}
The code is running fine and I'm getting the output I need.
My question is: Is there a better way to do that?
Currently I'm afraid to overload my Pi with too many open php sessions, therefore I'm starting the code only every 20min and also let the while loop sleep for 3 Min. But for improved accuracy I like to run the cronjob more often and also let the while loop sleep only for 30s.
My requirements are to stick to my PI and php code and not to use any available software like Home Assisant.io as it contradicts with my learning approach.
Any ideas or insights welcome.
Ideally it's a not the best approach to handling and measuring power consumption. It would be best if you created an API that accepts events like on/off or threshold hold limit extends from your IP devices. Further you can create logs and store them in databases.
Although, for your current problem here is one alternate solution.
Set your cron that runs every second.
function get_powerConsumption($machine, $watt_init, $threshold)
{
if ($watt_init < 2) {
exit();
}
$time = date("Y-m-d H:i");
$filename = $machine . '_power_consumption.log'; // expecting some machine identification name here. otherwise ignore prefix
$watt_current = json_combine(IPplug5);
if ($watt_current[0] >= $threshold) {
$data = array(
$time,
$watt_current[0]
);
file_put_contents($filename, json_encode($data) . "\n", FILE_APPEND);
} elseif ($watt_current[0] < $threshold) {
$data = array(
$time,
'stopped'
);
file_put_contents($filename, json_encode($data) . "\n", FILE_APPEND);
}
}
Create another cron to look up for stopped events logged in the file. if found process the calculation based on logged data like time and consumption. You can set this cron to run based on your need like every second or minute or after some interval.
Also, handle code to delete old logs, once stopped events found.
I would like to limit the access of a function i've created to once every 24 hour based on the users IP address. I would also like the PHP script to delete the MySQL record if it's older than 24 hours.
If the user already has used the function within 24 hours, show them a message and prevent the script from continue running.
If the user already has used the function but 24 hours has passed since he used the function, delete the MySQL record and let the script continue running.
I'm lost and as you can see i am also missing some statements for deleting old records (-24 hours)..
Could anyone provide me with an example of how to do this? Thanks
Get client's IP address and store it with current date and time if the record doesn't exist.
Fetch the record and add 24 hours to its date and time value and check it with the current date and time every time the script is executed.
You need if else conditional statements to check if the 24 hours time is over or not. Based on that, you will control the execution of the function you want to.
I think I don't want to write much of theory. Here, I've written the pattern what the code looks like:
if(!$record_in_db) {
// create record with the client's ip address and the current date and time
// invoke the function you want - This is the code to trigger the function first time for the new IP address
} else {
// fetch_record_from_db
// add 24 hours to its date and time value
// check it with current date and time
$record_date_time = new DateTime('22-12-2016 22:45:20'); // this value should be fetched from database
$record_date_time_by_24_hours = $record_date_time->modify('+1 day');
$current_date_time = new DateTime(date('d-m-Y H:i:s', strtotime('now')));
$date_time_diff = $current_date_time->diff($record_date_time_by_24_hours);
if($date_time_diff->invert == 0) {
// Do something
} else {
// update the date and time of the record to NOW which is current date and time
// invoke the function you want
}
}
I can't write you the whole code. I could only give you some hints. You need to build the code from it. Hope I've given you right hints that could help you.
I have a job site (in CI) and there can be x number of jobseekers.What i have to do is send revalent jobs according to users job category and location.So there is different message for different jobseeker.
i am using phpMailer to send email for now i have done
$subject = 'Revalent Jobs For Your Profile';
foreach ($job_receiving_users as $job_receiving_user){
$this->send_email->send_email(FROM_NOREPLY_EMAIL,ORG_NAME,$job_receiving_user['email'],$job_receiving_user['username'],$subject,$job_receiving_user['message']);
$time = time() + 10;
while( time() < $time){
// do nothing, just wait for 10 seconds to elapse
}
}
(There is phpMailer email sending method inside library send_email)
There is limit of 200 email per hour from server or can extend it to 500.
What i want to know is this good way to send email?
if i keep 10secod gap between every email will it keep my server busy.All sql actions were done above this code and $job_receiving_users is array of user email,message and username extracted above.
Base your code on the mailing list example provided with PHPMailer
What you're doing in your loop is called "busy waiting"; don't do it. PHP has several sleep functions; use them instead. For example:
$sendrate = 200; //Messages per hour
$delay = 1 / ($sendrate / 3600) * 1000000; //Microseconds per message
foreach ($job_receiving_users as $job_receiving_user) {
//$this->send_email->send_email(FROM_NOREPLY_EMAIL,ORG_NAME,$job_receiving_user['email'],$job_receiving_user['username'],$subject,$job_receiving_user['message']);
usleep($delay);
}
This will cause it to send a message every 18 seconds (200/hour), and the use of the sleep function will mean it consumes almost no CPU while it's waiting.
I am developing a desktop software where it charge user per execution the main action. For example say it will charge user 0.1$ for per PDF print.
and my software provide multithreading. .
so, if it run single thread it works fine :)
but the problem is if user run multiple thread at one (say 10/20 threads)
it (php) also continues user to allow the server/execution even balance get below zero..
though my php script check whether balance is positive ..
but after user run multiple threads balance become like -5.95$ or -25.75$ etc
and that is a big security/financial issue..
here is the code I am using:
<?php
$strSQL = "Select * from users where Email = '$strUser'";
$return = mysql_query($strSQL, $strDBConn);
$strDBData = mysql_fetch_array($return, MYSQL_ASSOC);
//checking balance
$strBalance = $strDBData['Balance'];
if($strBalance < 0)
{
// if balance 0 then exit so, my software/thread will not process further
mysql_close($strDBConn);
exit('Balance Exceed');
}
//rest of the codes that realted to service executaion
// code that substract the balnce
$dblCost = 0.25;
$strSQL = "Update users set Balance = Balance - '$dblCost' where Email = '$strUser'";
$return = mysql_query($strSQL, $strDBConn);
//rest finising codes
?>
any help/suggestion would be highly appreciated..
thanks in advance.
best regards
I think, this is a quite similar question:
What is equivalent of the C# lock statement in PHP?
First, try to switch away from the old "mysql" to somethin new, maybe some PDO like DB access ;).
Then, for getting around with multi-thread in php, it can be a good idea, to write a file for every userid (!) and lock this file, when there's a request. When file is locked in another thread, wait for x seconds for the file to be unlocked by the locker-thread. If it is not unlocked within time, something went wrong. When in locked-thread all went good, unlock the file after every operation needed.
Theoraticaly you will be good with then till there's a multi-thread soloution in PHP ;)
I would like to automate the process of sending this email. I mean when a condition is met then the email should automatically be sent to the given email addresses which is already given as hard-coded values. So for an example in my case a Technician has to complete 40jobs a day and if he finished 35 at the end of the day an email should be sent to the supervisor(provided his email id is already given) with Subject name and the body should be like ” The Technician 1234 has completed only 35 jobs for the day instead of 40. I was wondering how can implement this as Im very new to the field of PHP. Please anyone help me out. If possible please provide me with an example.
Thanks
Dilip
You could run a cron that uses the php mail function to send a report about each programmer at a set time each day. The cron script would look something like:
<?php
$to = 'admin#mydomain.com';//the set up email to mail too
$result = mysql_query('select programmer_id, job_count, job_requirement from table'); //query the database
while($job = mysql_fetch_object($result)){
mail($to,'Job counts for ' . $job->programmer_id,"Completed $job->job_count out of $job->job_requirement jobs","FROM: jobcounter#mydomain.com");
}
Have a script check the conditions and send emails, and run it periodically: http://www.google.com/search?q=cronjob
I'm assuming here that your problem is the triggering of the event, rather than the sending of the email itself.
In the example you described, you would need to have a script run at a certain time of day that would check for any condition that would require an email sending, and then send the email. Under any unix-like system, cron is the ideal solution to this. If you are on some kind of basic shared hosting you may not be able to set this up. In that case you would need to set up a task to run on a machine that you do have control over that would call a URL that would run the PHP script. This could be a cronjob, or a Scheduled Task under Windows.
If your example was switched around so that, say, an email was to be sent as soon as a technician completed 40 jobs then you would be able to send the email as part of the script that handled the form submission from the technician whenever he completed a task.
Setup a Cron Job that runs at the "end of the day":
23 55 * * * /path/to/php /path/to/script.php
Have it run a PHP script that can query your Job Store for whatever condition you want to check. For example with Job Store being a database.
$db = new PDO(/* config */);
$result = $pdo->query(
'SELECT count(id) as "tasks_done"
FROM tasks WHERE engineer = "Tom"
AND finished_at = now()');
$result = $result->fetchAll();
if($result[0]['tasks_done'] < 40) {
mail( ... )
}
If the condition is met, send the mail. The above needs refining of course. Dont expect being able to copy/paste it.
Also see:
What is the best method for scheduled tasks in PHP
http://greenservr.com/projects/crontab/crontab.phps
you should use mail() function:
$technicianId = 1234;
$jobsNeeded = 40;
$jobsDone = getJobsDone($technicianId);
if ($jobsDone <= $jobsNeeded) {
mail('supervisor#yourcompany.com', 'Technician '.$technicianId.' slacking', 'The Technician '.$technicianId.' has completed only '.$jobsDone.' jobs for the day instead of '.$jobsNeeded);
}
Could have a cronjob that runs at the end of each day which checks what each technician has done and emails it to the manager.