Run php calculations when the browser is closed - php

I'm trying to create a YouTube-like service where the content creator is paid for their content however I'm a bit stuck.
The website needs to calculate the amount of views a content creator gets a month to calculate how much they need to be paid and then through PayPal API pay them by the end of the month. The problem is that this needs to be done even when the page is closed. I assume this is done on a server but I not sure if that's the case or even how to do it.
Thanks

Just googling real quick on cron, I found this website: https://www.pantz.org/software/cron/croninfo.html
I have used cron a lot before and the information here seems adequate to answer your question; it at least will arm you with the knowledge needed to do what is required.
An example for a cron job could be the following:
50 * * * * /myTask.php
What this says is "run this script 'myTask.php' every 50 minutes, every hour, every day of the month, every month, every day of the week" - simply put, run every 50 minutes.
The aforementioned task can be added to the crontabs file by using the following command from the terminal crontab -e

I found the solution. It turns out that the service hosting my website has an option to run cron jobs internally so I can make a script to loop through all the users, calculate their view earnings and pay them and run it at the beginning or each month.

Related

handling scheduled/time bound tasks in enterprise web application

On the surface it looks very simple problem that I am facing. In an enterprise web app (LAMP stack) we need to add some time based & schedule based tasks. Some examples are
when a user logs in and has stayed active for more than 30 minutes, send them a lucky coupon.
send a newsletter to subscribers every Monday. [easily handled by a cron job]
If a user does not login for 3 days, start stalking her. [doable by cron job but ...]
deduct phone bill amount from user account on 1st working day of every month at 9.
repeat failed deduction every subsequent work day at 9 for a max of 15 retries.
I hope that give you an idea of what is going on that needs to be handled.
At the moment we have cron jobs of almost every possible situation and they are kind of working but as you can see with the above scenarios, we are forced to run those crons almost every second (bit exaggeration but almost).
To handle the issue more elegantly and better implement the ddd concepts, we are thinking to make clock ticking as first class citizen of the application.
We would like to make a simple central clock ticker class, that will emit ticks as time events every second.
The ticks will be published to the central event bus.
And all the classes that are interested to act on the tick, will subscribe to the event bus.
What I am unable to figure out yet is that this will result in making a lot of subscriber/registrant classes code to run on every tick. As this is already the case with cron, could there be a better way to handle the subscription part so that a specific subscription is notified only when it needs to be notified?
And before we even get into solving this problem the way I am proposing, is there is a better way to handle this kind of problems? The key point in this whole scenario seems to be how to trigger something X based on how much time has passed since something Y happened in the domain. I believe I am not the first one to face this issue and this problem must have been long solved already but I am unable to stumble upon any road sign pointing me to the right direction.
The way I have handled this in the past is to queue commands as soon as I know something should happen and then the scheduler will fire off the commands when the time has come.
The scheduler is simply a process that runs as a service and wakes every N milliseconds to find any commands that have passed their ScheduledTime.
For example:
The user has logged in. Queue a command for 30 minutes hence to give them a coupon. After 30 minutes, the scheduler will send the command. If the session is still active, then the command is accepted and a coupon is presented. Otherwise, it simply does nothing.
You also mention several examples that are best handled by a traditional scheduler (cron as you mentioned) and will fire off a batch command. Depending on how knowledgeable your domain is about things like newsletters, you would either issue individual commands to your domain objects or simply pull a report and run a job to send emails.
If you do handle these types of processes in your domain, then your domain should also queue the next command. A saga or process manager would be most suitable for this type of operation. E.g.
CreateNewsletter (This is the batch) -> NewsletterCreated
Accounts.Each(SendAccountNewsletter) -> AccountNewsletterSent
NewsletterCompleted (This is the batch) ->
Queue(command: CreateNewsletter, when: NextMondayAt9) (This is the next batch)
Hope that helps.
P.S. If you publish ticks on your bus, you will have a ton of noise to filter through.

Uptime Monitor PHP

I am trying to create a system to monitor a Minecraft server using PHP. It will then periodically(every 10 minutes) check the status of the server. If the server is unreachable, it will time for how long it went down and then store that in a database.
I have created the code to check the server status but am struggling with timing for how long the server went off. What ways could I time the downtime ?
You cant calculate the downtime, I suggest that when a downtime is occured, you check it again in every one minute until the uptime, and get the difference of first down time and next uptime, this gives you a downtime with accuracy of one minute
you can update to the database the last up-time and calculate downtime with it and overwrite the downtime every time you calculate it
For this type of tasks, crontab is a great tool: it's a file that will execute defined commands at the time you set them.
you can use your isp's cpanel tool named cron jobs. from there it's pretty easy to create a cron job. just enter the command portion of the three lines below.
if you can't use this tool or prefer to write directly into your crontab, those lines are the resultant command (from http://www.pantz.org/software/cron/croninfo.html):
# Minute Hour Day of Month Month Day of Week Command
# (0-59) (0-23) (1-31) (1-12 or Jan-Dec) (0-6 or Sun-Sat)
0,10,20,30,40,50 * * * * php /home/yourdomain/public_html/test.php
my test.php:
mail('mail#internets.com','time();',date('H:i:s',time()));
this mails the time each ten minutes. from there on you patch your status checker code in test.php (or whatever name you want) and insert this data in database. I don't have enough information to provide code to calculate time. What is your data structure? How do you interact with your database?

Running a PHP script or function at an exact point in the future

I'm currently working on a browser game with a PHP backend that needs to perform certain checks at specific, changing points in the future. Cron jobs don't really cut it for me as I need precision at the level of seconds. Here's some background information:
The game is multiplayer and turn-based
On creation of a game room the game creator can specify the maximum amount of time taken per action (30 seconds - 24 hours)
Once a player performs an action, they should only have the specified amount of time to perform the next, or the turn goes to the player next in line.
For obvious reasons I can't just keep track of time through Javascript, as this would be far too easy to manipulate. I also can't schedule a cron job every minute as it may be up to 30 seconds late.
What would be the most efficient way to tackle this problem? I can't imagine querying a database every second would be very server-friendly, but it is the direction I am currently leaning towards[1].
Any help or feedback would be much appreciated!
[1]:
A user makes a move
A PHP function is called that sets 'switchTurnTime' in the MySQL table's game row to 'TIMESTAMP'
A PHP script that is always running in the background queries the table for any games where the 'switchTurnTime' has passed, switches the turn and resets the time.
You can always use a queue or daemon. This only works if you have shell access to the server.
https://stackoverflow.com/a/858924/890975
Every time you need an action to occur at a specific time, add it to a queue with a delay. I've used beanstalkd with varying levels of success.
You have lots of options this way. Here's two examples with 6 second intervals:
Use a cron job every minute to add 10 jobs, each with a delay of 6 seconds
Write a simple PHP script that runs in the background (daemon) to adds an a new job to the queue every 6 seconds
I'm going with the following approach for now, since it seems to be the easiest to implement and test, as well as deploy on different kinds of servers/ hosting, while still acting reliably.
Set up a cron job to run a PHP script every minute.
Within that script, first do a query to find candidates that will have their endtime within this minute.
Start a while-loop, that runs until 59 seconds have passed.
Inside this loop, check the remianing time for each candidate.
If teh time limit has passed, do another query on that specific candidate to ensure the endtime hasn't changed.
If it has, re-add it to the candidates queue as nescessary. If not, act accordingly (in my case: switch the turn to the next player).
Hope this will help somebody in the future, cheers!

php: I want a code to be executed every 1 minute

I will try be clear and specific :)
So i have a website, where people purchase stuff from each other.
To keep everything organised, when someone buys something from another user, That purchase will be moved to a table in database, called Pending. (Note: The purchased is not processed yet)
(so all purchases will be moved and queued into this 'Pending' table)
Now what I want to do is, that this table 'Pending', starts processing 1 purchase at a time automatically (let's say 1 purchase every one minute --> if there are any ofcourse).
Now I have no idea how to do this, if someone can atleast give me a hint on what can I use or what to look for, in order to do this.
Note: am using php & mysql
Thanks in advance :D :)
You can write a PHP script to be executed by a cron job. PHP doesn't have to be executed from a browser request, it can be run form the command-line. Cron would make use of this functionality.
The crontab line to execute a command every minute would be as follows:
* * * * * /path/to/script.php
Each column has a * indicating "any value", so this indicates to run the script "any minute, any hour, any day, any month, any day of week"
A cronjob is going to be your best bet, http://en.wikipedia.org/wiki/Cron
Make some file named MovePending.php with a MySQL query that 'moves' the purchases from Pending to Processed, and run it every minute via a cron job.

Multiple time-critical background tasks

I'm new to PHP, so I need some guidance as to which would be the simplest and/or elegant solution to the following problem:
I'm working on a project which has a table with as many as 500,000 records, at user specified periods, a background task must be started which will invoke a command line application on the server that does the magic, the problem is, at each 1 minute or so, I need to check on all 500,000 records(and counting) if something needs to be done.
As the title says, it is time-critical, this means that a maximum of 1 minute delay can be allowed between the time expected by the user and the time that the task is executed, of course the less delay, the better.
Thus far, I can only think of a very dirty option, have a simple utility app that runs on the server, that at each minute, will make multiple requests to the server, example:
check records between 1 and 100,000;
check records between 100,000 and 200,000;
etc. you get the point;
and the server basically starts a task for each bulk of 100,000 records or less, but it seems to me that there must be a faster approach, something similar to facebook's notification.
Additional info:
server is Windows 2008
using apache + php
EDIT 1
users have an average of 3 tasks per day at about 6-8 hours interval
more than half of the tasks can be at least 1 time per day executed at the same time[!]
Any suggestion is highly appreciated!
The easiest approach would be using a persistent task that runs the whole time and receives notification about records that need to be processed. Then it could process them immediately or, in case it needs to be processed at a certain time, it could sleep until either that time is reached or another notification arrives.
I think I gave this question more than enough time, I will stick to a utility application(that sits on the server) that will make requests to a URL accessible only from the server's IP which will spawn a new thread for each task if multiple tasks needs to be executed at the same time, it's not really scalable but it will have to do for now.

Categories