我用laravel 6做了一个项目,我的数据库表名是建筑物的id – wood – clay – iron – crop – created_at – updated_at1 – 25 – 54 – 57 – 63 – null – null,所以我做了jquery ajax代码来增加每列1作为测试。
游戏.js
$(document).ready(function(){
setInterval(function(){
var dataString = 'id=1';
$.ajaxSetup({ headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')} });
$.ajax({
type: "post",
url: "{{ route('upgradeBuildings') }}",
data: dataString,
cache: false,
beforeSend: function(){},
success: function(data){
$('.x').html(data);
},
error: function(err){console.log(err);}
});
}, 1000);
});
游戏
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Logs;
use App\Buildings;
class LogsController extends Controller
{
public function upgradeBuildings(Request $request)
{
$id = $request->id;
$updatecount = Buildings::increment("wood", "1");
$buildings = Buildings::get()->first();
$wood = $buildings->wood;
return Response($wood);
}
public function village()
{
$buildings = Buildings::get();
$users = DB::table('users')->get();
$settings = DB::table('settings')->get()->first();
return view('game.village', compact('buildings', 'settings', 'users'));
}
}
但当我打开有game.js的村名页面时,这些代码就能用了
我想让这段代码在我没有打开这个页面的情况下工作。
解决方案:
你可以创建一个 Artisan
命令,并运行 Task Scheduling
技巧部分是每秒钟运行一次函数。
可以使用一个变通方法。
<?php
namespace App\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
class upgradeBuilding extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'buildings:upgrade';
/**
* The console command description.
*
* @var string
*/
protected $description = 'run every seconds';
/**
* Create a new command instance.
*
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$count = 0;
while ($count < 59) {
$startTime = Carbon::now();
// Your logic here
$endTime = Carbon::now();
$totalDuration = $endTime->diffInSeconds($startTime);
if($totalDuration > 0) {
$count += $totalDuration;
}
else {
$count++;
}
sleep(1);
}
}
}
那就是每分钟调度一次命令
$schedule->command('buildings:upgrade')->everyMinute();