How to delete mysql data from table at midnight? - javascript

I have a mysql table and I want it to be "emptied" every night at midnight. I have searched for an answer on the web and came across nothing that seemed to help me. I had this idea of using javascript to get the current time and then run an if statement and see if it is equal to midnight and if it was to execute a php script that deleted the information.
Javascript:
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
if(t == 12:00:00 AM){
$.ajax({
URL: 'delete.php';
});
};
};
delete.php:
<?php
require 'connect.php';
mysql_query("DELETE * FROM messages;");
?>
I have tested this by setting the time in the if statement to a time a few minutes ahead of my actual time and it does not work.

Implementing your own event scheduler, especially as a web page using JavaScript is a bad idea.
Use for that either
a cron job to run DELETE statement through the mysql command line interface
/path/to/mysql -u<user> -p"<password>" <db_name> -e "delete from messages"
or a MySQL event, e.g.
CREATE EVENT delete_messages_at_midnight 
ON SCHEDULE EVERY 1 DAY STARTS CURDATE() + INTERVAL 1 DAY
DO DELETE FROM messages;
If you go with MySQL event approach:
use SHOW PROCESSLIST to check if the event scheduler is enabled. If it's ON you should see a process "Daemon" by user "event_scheduler".
use SET GLOBAL event_scheduler = ON;to enable the scheduler if it's currently not enabled.
More on configuring event scheduler read here

Related

How to run cron jobs according to user's timezone in nodeJs?

I am using cron jobs to reset a particular field back to zero let's call it a streak I am trying to reset current streak of a user. so for that I am running a cron job at 11:59 to reset the data if user doesn't perform a particular task,But it's running according to UTC time. I want it to run according to users timezone who is using the application. Is it possible to run it according to different timezone or anyone could suggest any other way to do so.
You should set the time with a lib like http://momentjs.com/timezone/docs/.
var a = moment.tz("2013-11-18 11:55", "America/Toronto");
or
You should try CronJob npm package
new CronJob(
targetTime,
async function () {
await donsomething
},
null,
true,
time_zone
);

Show same content at same time in different browser

I am developing a numbers game where users will buy numbers and after 2 days winners will be drawn.
I am using PHP for the backend and jQuery for the frontend.
My problem is when drawing occurred user on different browser can't see same numbers, these draw numbers are being generated by PHP.
I was thinking maybe I can build these game by PHP and Javascript but it looks not easy. Can you guys please suggest some alternative? How can I improve this code to show the same number on the different browser?
I have the idea that it is not possible to generate a random number for each request. Maybe I can save the number in the database and then get this number in PHP such that the number will be unique for each request.
The actual issue is to create the same content for each user in different browsers. Any help would be really appreciated.
Javascript:
var myTimer = setInterval(checkDrawDate, 1000);
function checkDrawDate() {
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
var x = new Date(dateTime);
var y = new Date("{{$drawDate}}"); //this is laravel variable which contain drawdate e.g. 2017-07-05
if(x >= y){
drawNumber();
}
}
function drawNumber(){
$.get("{{ route('ajaxcomparepowerball') }}",{'gameId': gameid}, function(res){
$('#mybets').html(res.html);
});
}
PHP:
public function ajaxDrawNumber(Request $req){
return rand(0,49);
}
A Cron Job will be needed to implement this functionality. As you are drawing a number on particular time (after $drawDate in your case). So the cron job will execute once in day, check whether $drawDate for each game is today or passed. If condition true, $drawDate <= now, call a function to generate random draw number rand(0,49) and save it to database corresponding to gameid of matched games(having $drawDate <= now).
By doing this, a lot Javascript work will be reduced. In JS, then need to hit an ajax request with gameid to fetch record having draw number for particular game from database. If record not found, it means random number not drawn yet.
I think you are using Laravel, so to schedule tasks in laravel visit here.
Here some possible solutions.
If you need the same data modified for users in real time I think the best option is WebRTC, quick start here. And here a simple example sending strings in real time between clients.
If you also need interaction server to client you could use server-sent events.
You could perform a bidirectional communication between browser and a server using WebSockets. You can send and receive event-driven responses. Using a database you could communicate two clients.
The easiest is using a database to store the information and perform ajax to send data to the server (and database) and server-sent events to send data to the clients.
Basic Server-sent event example:
Javacript:
var evtSource = new EventSource("myserver.php");
evtSource.onmessage = function(e) {
// listening for new messages here
alert(e.data)// e.data is mynumber
}
Php (myserver.php)
<?php
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream\n\n");
while (1) {
//perform a query in your database with your driver
$result = mysql_query("SELECT mynumber FROM mytable WHERE user = 1");
$row = mysql_fetch_assoc($result);
echo $row['mynumber'];//<-- sending mynumber to client
ob_end_flush();
flush();
sleep(1);// <-- this is every second, but you could fire this with ajax or some other event.
}
This code send a number from server to a client that is listening. If a user made a change, one possibility is that client send an ajax to update some value in the database. So, at the same time, the ajax server could send this as an update to clients listening. In that way the whole process is completed.
I think all you need is this. Call a function in every, say 5 seconds or less and fetch data from server and update it in the page.
window.setInterval(function(){
updateNumber();
}, 5000);// set for every five seconds
function updateNumber(){
//ajax code to fetch live data and append the data in the numbers container
}
And dont forget to cross check the data before saving the numbers in the server.
Hope it helps.!!!
To save and maintain users state, key value store like Aerospike can be used. It is very easy to save and retrieve data in key value store. In above case we just have to generate a unique key using gameId, userId and date. And save user's data against the unique key.
To get started with Aerospike php client following is Aerospike php client
If data is present against the unique id for that particular user just return it, else create the new random number save it against the unique key and return it. Please be careful while creating unique key. Instead of using server side date-time please send date in ajax call request so there will not be any issue with time zone. It will be always user's timezone and there will not be any issue if server is in different timezone and user is in different timezone.
function drawNumber(){
$.get("{{ route('ajaxcomparepowerball') }}",{'gameId': gameid,'date':user-timezone-date}, function(res){
$('#mybets').html(res.html);
});
}
Here "user-timezone-date" should be fix date format like 'MM-dd-yy' which will indicate the same day. hours or seconds should not be included while generating unique key otherwise at the time of retrieving the user's state; generating particular unique will be changed every hour or every second and whole purpose of of doing this will be shattered.
I am new to StackOverFlow so I am not able to comment on the answers. In case of corn job as well we have to be careful with time-zones if server and users are in different time zones. Otherwise user's will see different random number before user's day is complete. Please improve answer by commenting on it and suggestions are always welcome.

Setting up a delay notification with php

I need to write a php function for sending a Telegram notification after 4 hours.
With the application i'm posting data into a SQL db, after I pressed the Submit button, i need that a php function starts and after 2 days sends to my Telegram channel a notification, with some of the data that i've posted into the db record.
For the posting part and Telegram part i'm ok, i've already linked the website to the channel and normal notifications from php work fine, but i need some advice on the "reminder" part.
I was thinking about some date() function and post the value in to the record, make another var with the date + 2days e make some for or while cycle but i don't think that this can works. Some advice?
I'm new to php, maybe i dont know some function that could help me?
Add to your table a column and name it notification_send and give it a default value of 0
Create a crontab that calls a php file for example:
*/60 * * * * php -f /etc/www/my_notification.php : calls the file every 60 mintues
In this file create a query that selects all the data with the notification_send = 0 then check if the current_date - date column of each row => 2 days :
If so : update the notification_send value to 1 and send your notification
As I commented, your approach is right. As you asked something more, though, I chose to write an answer.
As you asked, when you send a Telegram notification you have to send a reminder notification after 2 days (48h). If I'm right it's an e-mail.
First of all, as you said, you have to create a column to warn when the remember should be send.
Also, to know if the reminder has been sent or not you have to create another column. It could be a flag (true/false) or a datetime column (null = not sent, filled = sent).
Besides that, a cronjob or schedule have to call a PHP script. I'll show to you an example of a PHP script.
I'll call the table as reminder and the column sendIn and isSent.
//select only the reminder that has the sendIn lesser than now and that not has been sent
$statement = $pdo->query("SELECT * FROM reminder WHERE sendIn <= NOW() AND isSent is null");
//prepared statement to update the reminder sent
$updateStatement = $pdo->query("UPDATE reminder SET isSent = NOW() WHERE id = :id");
foreach($statement as $reminder)
{
/**
script to send the reminder
**/
//update the reminder
$updateStatement->execute(array(':id' , $reminder['id']));
}
To create a cronjob, you could take a look here:
https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job
You don't need to delete the cron, just let it run periodically and send all your reminders.

how can I make a countdown timer perform an action when it runs out?

this is my very first question here and may not meet some standards, for that i apologize in advance.
I have a site developed in laravel 5 where the users register and are expected to make take an action within a specific period after registration. I have included a countdown timer for that purpose (the time code is shown below). Now I need to automatically remove a user record from the database when the time runs out. Please how can I do that?
the timer code is:
<div class="getting-started"></div>
<?php
$time = strtotime($user['updated_at'].'+24 hours');
$countdown = strftime('%Y/%m/%d %H:%M:%S',$time);
?>
<script type="text/javascript">
$(".getting-started")
.countdown("{{$countdown}}", function(event) {
$(this).text(
event.strftime('%H:%M:%S')
);
});
</script>
If you want something to happen on the server, then you should maintain the timer on the server side, not the client side. Otherwise, the user can simply change the timer or otherwise block the action that the expiration is meant to trigger. I would store a timestamp with the user record, noting when it was created. Then write a script to loop over all records that are older than your threshold and perform the desired action on them. Then run this script via a cron that fires at a regular interval.

variable value on page change

I am new in javascript and php. I am creatng an admin panel in which I have an option for the user to play game. But the issue is, every game have a specific time period say 30 mins. So, what I want is that if a user have started the game, the count down must be started and if user once switch from that page to another page, still the counter must be counting and after 30 mins it should end the game.
For example I am on http://www.examplec.com/Game1 my count down of 30 min will start. If I switch from that page to another like http://www.example.com/order then the counter should still count the total time and when its expired, end it and send query to database.
Kindly reply if anyone know the solution. I have already find a solution using session but I want more efficient solution. One more thing a single user can play more than 1 game.
when your game start set a session of current time like this
$_SESSION['game_start_time'] = strtotime(date('d-M-Y g:i:s A')); // it will give you complete current timestamp.
and now check it on every page by including
if(isset($_SESSION['game_start_time']))
{
$game_start_time = $_SESSION['game_start_time'];
$current_time = strtotime(date('d-M-Y g:i:s A'));
$time_diff = $current_time - $game_start_time;
if($time_diff>(30*60))
{
//expire 30 minutes your code is here
}
else
{
// action if require to do when below 30 minutes of game start.
}
}
What you could do is create a table to keep track of the time, this is not the most efficient way but it would be secure.
So create a new table called gametrack with the following fiels:
id
userid
gameid
timestarted
etc
so when a user starts a game you insert a record with user info.
Next you need to edit the game page. In the game page you could place a jquery code to request for update on the time.
function gameStatus(){
$.ajax({
url: 'status.php?gid=[GAMEID]',
success: function(data) {
if(data == 1) {
//DO SOMETHING, REFRESH THE PAGE, STOP THE GAME ETC
}
}
});
}
setInterval("gameStatus()",10000);
the code above would request status.php every 10 seconds, you need to pass the gameid to the file and assuming that the user is registered you can use session to get user info and return 1 if 30 mins has passed.
You can mix this solution with Satish's Answer to use Sessions instead of Databases and still get a live count down with the jquery code above.
You can try this with localStorage
When you want to set variable:
var name = "value";
localStorage.setItem("someVarName", name);
And in any page (like when the page has loaded), get it like:
var Name = localStorage.getItem("someVarName");
Browser compatibility caniuse.com/namevalue-storage
Demo

Categories

Resources